Skip to content

Commit

Permalink
LESS: Fixes source map path issues & refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
am11 committed Dec 23, 2013
1 parent c8de293 commit 3a4950f
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 40 deletions.
1 change: 0 additions & 1 deletion EditorExtensions/CodeAnalysis.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
<RuleSet Name="Copy of Microsoft All Rules" Description="This rule set contains all rules. Running this rule set may result in a large number of warnings being reported. Use this rule set to get a comprehensive picture of all issues in your code. This can help you decide which of the more focused rule sets are most appropriate to run for your projects." ToolsVersion="12.0">
<IncludeAll Action="Warning" />
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
<Rule Id="CA1002" Action="None" />
<Rule Id="CA1006" Action="None" />
<Rule Id="CA1020" Action="None" />
<Rule Id="CA1026" Action="None" />
Expand Down
7 changes: 3 additions & 4 deletions EditorExtensions/Margin/LessCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ public static class LessCompiler
private static readonly string node = Path.Combine(webEssentialsNodeDir, @"node.exe");
private static readonly Regex errorParser = new Regex(@"^(.+) in (.+) on line (\d+), column (\d+):$", RegexOptions.Multiline);

public static async Task<CompilerResult> Compile(string fileName, string targetFileName = null, string sourceMapRootPath = null)
public static async Task<CompilerResult> Compile(string fileName, string targetFileName = null)
{
string output = Path.GetTempFileName();
string arguments = String.Format("--no-color --relative-urls \"{0}\" \"{1}\"", fileName, output);
string fileNameWithoutPath = Path.GetFileName(fileName);
string sourceMapArguments = (string.IsNullOrEmpty(sourceMapRootPath)) ? "" : String.Format("--source-map-rootpath=\"{0}\" ", sourceMapRootPath.Replace("\\", "/"));

if (WESettings.GetBoolean(WESettings.Keys.LessSourceMaps))
arguments = String.Format("--no-color --relative-urls {0}--source-map=\"{1}.map\" \"{2}\" \"{3}\"", sourceMapArguments, fileNameWithoutPath, fileName, output);
arguments = String.Format("--no-color --relative-urls --source-map=\"{0}.map\" \"{1}\" \"{2}\"",
targetFileName, fileName, output);

ProcessStartInfo start = new ProcessStartInfo(String.Format("\"{0}\" \"{1}\"", (File.Exists(node)) ? node : "node", lessCompiler))
{
Expand Down
57 changes: 39 additions & 18 deletions EditorExtensions/Margin/LessMargin.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
Expand All @@ -12,6 +13,7 @@ namespace MadsKristensen.EditorExtensions
public class LessMargin : MarginBase
{
public const string MarginName = "LessMargin";
private static readonly Regex _sourceMapinCSS = new Regex(@"\/\*#([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/", RegexOptions.Multiline);

public LessMargin(string contentType, string source, bool showMargin, ITextDocument document)
: base(source, MarginName, contentType, showMargin, document)
Expand All @@ -34,7 +36,7 @@ protected override async void StartCompiler(string source)

Logger.Log("LESS: Compiling " + Path.GetFileName(lessFilePath));

var result = await LessCompiler.Compile(lessFilePath, cssFilename, Path.GetDirectoryName(lessFilePath));
var result = await LessCompiler.Compile(lessFilePath, cssFilename);

if (result.IsSuccess)
{
Expand Down Expand Up @@ -96,37 +98,56 @@ protected override bool CanWriteToDisk(string source)
return true;// !string.IsNullOrWhiteSpace(stylesheet.Text);
}

protected override string UpdateLessSourceMapUrls(string content, string oldFileName, string newFileName)
protected override string UpdateLessSourceMapUrls(string content, string sourceFileName, string compiledFileName)
{
if (!WESettings.GetBoolean(WESettings.Keys.LessSourceMaps))
return content;
dynamic jsonSourceMap = null;
string sourceMapFilename = oldFileName + ".map";
// Read JSON map file and deserialize.
string sourceMapContents = File.ReadAllText(sourceMapFilename);

jsonSourceMap = Json.Decode(sourceMapContents);
string sourceMapFilename = compiledFileName + ".map";

if (jsonSourceMap == null)
if (!File.Exists(sourceFileName))
return content;

var updatedFileContent = GetUpdatedSourceMapFileContent(sourceFileName, compiledFileName, sourceMapFilename);

if (updatedFileContent == null)
return content;

string projectRoot = ProjectHelpers.GetRootFolder(ProjectHelpers.GetActiveProject());
string cssNetworkPath = FileHelpers.RelativePath(oldFileName, newFileName);
string sourceMapRelativePath = FileHelpers.RelativePath(oldFileName, sourceMapFilename);
WriteFile(updatedFileContent, sourceMapFilename, true, false);

return UpdateSourceLinkInCssComment(content, FileHelpers.RelativePath(sourceMapFilename, sourceFileName));
}

private static string GetUpdatedSourceMapFileContent(string lessFileName, string cssFileName, string sourceMapFilename)
{
// Read JSON map file and deserialize.
dynamic jsonSourceMap = Json.Decode(File.ReadAllText(sourceMapFilename));

if (jsonSourceMap == null)
return null;

jsonSourceMap.sources = new List<dynamic>(jsonSourceMap.sources);
jsonSourceMap.sources = UpdateSourcePaths(new List<dynamic>(jsonSourceMap.sources), cssFileName, lessFileName);
jsonSourceMap.names = new List<dynamic>(jsonSourceMap.names);
jsonSourceMap.file = cssNetworkPath;
jsonSourceMap.file = FileHelpers.RelativePath(lessFileName, cssFileName);

for (int i = 0; i < jsonSourceMap.sources.Count; ++i)
return Json.Encode(jsonSourceMap);
}

private static List<dynamic> UpdateSourcePaths(List<dynamic> sources, string cssFileName, string lessFileName)
{
for (int i = 0; i < sources.Count; ++i)
{
jsonSourceMap.sources[i] = FileHelpers.RelativePath(newFileName, projectRoot + jsonSourceMap.sources[i]);
sources[i] = FileHelpers.RelativePath(cssFileName,
File.Exists(sources[i]) ? sources[i] : lessFileName);
}

WriteFile(Json.Encode(jsonSourceMap), sourceMapFilename, File.Exists(sourceMapFilename), false);
return sources;
}

// Fixed sourceMappingURL comment in CSS file with network accessible path.
return Regex.Replace(content, @"\/\*#([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/", "/*# sourceMappingURL=" + sourceMapRelativePath + "*/");
private static string UpdateSourceLinkInCssComment(string content, string sourceMapRelativePath)
{ // Fixed sourceMappingURL comment in CSS file with network accessible path.
return _sourceMapinCSS.Replace(content,
String.Format(CultureInfo.CurrentCulture, "/*# sourceMappingURL={0} */", sourceMapRelativePath));
}
}
}
8 changes: 2 additions & 6 deletions EditorExtensions/Margin/LessProjectCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,14 @@ public static void CompileProject(Project project)

private static async Task Compile(Project project)
{
string projectRoot = ProjectHelpers.GetRootFolder(project);
var files = Directory.EnumerateFiles(projectRoot, "*.less", SearchOption.AllDirectories).Where(CanCompile);
string fileBasePath = string.Empty;
var files = Directory.EnumerateFiles(ProjectHelpers.GetRootFolder(project), "*.less", SearchOption.AllDirectories).Where(CanCompile);

if (!files.Any()) return;

fileBasePath = "/" + Path.GetDirectoryName(FileHelpers.RelativePath(projectRoot, files.First())).Replace("\\", "/");

foreach (string file in files)
{
string cssFileName = MarginBase.GetCompiledFileName(file, ".css", WESettings.GetString(WESettings.Keys.LessCompileToLocation));
var result = await LessCompiler.Compile(file, cssFileName, projectRoot + fileBasePath);
var result = await LessCompiler.Compile(file, cssFileName);

if (result.IsSuccess)
WriteResult(result, cssFileName);
Expand Down
15 changes: 6 additions & 9 deletions EditorExtensions/Margin/MarginBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,11 +254,10 @@ protected string WriteCompiledFile(string content, string currentFileName)
return string.Empty;
}

bool fileExist = File.Exists(fileName);
bool fileWritten = false;

ProjectHelpers.CheckOutFileFromSourceControl(fileName);
fileWritten = WriteFile(content, fileName, fileExist, fileWritten);

bool fileExist = File.Exists(fileName);
bool fileWritten = WriteFile(content, fileName, fileExist, false);

if (!fileExist && fileWritten)
{
Expand All @@ -268,16 +267,14 @@ protected string WriteCompiledFile(string content, string currentFileName)
return content;
}

protected virtual string UpdateLessSourceMapUrls(string content, string oldFileName, string newFileName)
{
// If not overridden by derived, return content as is.
protected virtual string UpdateLessSourceMapUrls(string content, string sourceFileName, string compiledFileName)
{ // If not overridden by derived, return content as is.
return content;
}

public static string GetCompiledFileName(string sourceFileName, string compiledExtension, string customFolder)
{
string sourceExtension = Path.GetExtension(sourceFileName);
string compiledFileName = Path.GetFileName(sourceFileName).Replace(sourceExtension, compiledExtension);
string compiledFileName = Path.GetFileName(Path.ChangeExtension(sourceFileName, compiledExtension));
string sourceDir = Path.GetDirectoryName(sourceFileName);
string compiledDir;
string rootDir = ProjectHelpers.GetRootFolder();
Expand Down
3 changes: 1 addition & 2 deletions WebEssentialsTests/Tests/LESS/LessCompilationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ public class LessCompilationTests
#region Helper Methods
private static async Task<string> CompileLess(string fileName, string targetFilename = null)
{
string siteMapPath = "/" + Path.GetDirectoryName(FileHelpers.RelativePath(BaseDirectory, fileName)).Replace("\\", "/");
var result = await LessCompiler.Compile(fileName, targetFilename, siteMapPath);
var result = await LessCompiler.Compile(fileName, targetFilename);

if (result.IsSuccess)
{
Expand Down

0 comments on commit 3a4950f

Please sign in to comment.