Skip to content

Commit

Permalink
Merge pull request #344 from am11/master
Browse files Browse the repository at this point in the history
LESS (Fixed #346: source map path fixes & code refactoring) and Analysis (warning fixes)
  • Loading branch information
madskristensen committed Dec 23, 2013
2 parents c8de293 + de43b97 commit c226c2d
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static bool IsPixelPushingModeEnabled
}
}
}
public static List<Regex> IgnoreList
public static IEnumerable<Regex> IgnoreList
{
get
{
Expand Down
2 changes: 1 addition & 1 deletion EditorExtensions/BrowserLink/UnusedCss/RawRuleUsage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class RawRuleUsage : IEquatable<RawRuleUsage>
[JsonProperty]
public string Selector { get; set; }
[JsonProperty]
public List<SourceLocation> SourceLocations { get; private set; }
public IEnumerable<SourceLocation> SourceLocations { get; private set; }

public RawRuleUsage()
{
Expand Down
2 changes: 1 addition & 1 deletion EditorExtensions/BrowserLink/UnusedCss/SessionResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class SessionResult : IUsageDataSource, IResolutionRequiredDataSource
[JsonProperty]
public bool Continue { get; set; }
[JsonProperty]
public List<string> Sheets { get; private set; }
public IEnumerable<string> Sheets { get; private set; }

public IEnumerable<IStylingRule> AllRules
{
Expand Down
4 changes: 2 additions & 2 deletions EditorExtensions/BrowserLink/UnusedCss/UnusedCssExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ public class UnusedCssExtension : BrowserLinkExtension
public static bool IsAnyConnectionAlive { get { return ExtensionByConnection.Count > 0; } }
public BrowserLinkConnection Connection { get { return _connection; } }
public bool IsRecording { get; private set; }
public static List<string> IgnoreList
public static IEnumerable<string> IgnoreList
{
get
{
var ignorePatterns = WESettings.GetString(WESettings.Keys.UnusedCss_IgnorePatterns) ?? "";

return ignorePatterns.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
return ignorePatterns.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
}
}
private static List<string> IgnorePatternList
Expand Down
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: 6 additions & 1 deletion EditorExtensions/Commands/Code/IntellisenseWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,17 @@ public class IntellisenseObject
public string FullName { get; set; }
public bool IsEnum { get; set; }
public string Summary { get; set; }
public List<IntellisenseProperty> Properties { get; private set; }
public IList<IntellisenseProperty> Properties { get; private set; }

public IntellisenseObject()
{
Properties = new List<IntellisenseProperty>();
}

public IntellisenseObject(IList<IntellisenseProperty> properties)
{
Properties = properties;
}
}

public class IntellisenseProperty
Expand Down
7 changes: 3 additions & 4 deletions EditorExtensions/Commands/Code/ScriptIntellisenseListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,19 +163,18 @@ private static void ProcessEnum(CodeEnum element, List<IntellisenseObject> list)

private static void ProcessClass(CodeClass cc, List<IntellisenseObject> list)
{
var props = GetProperties(cc.Members, new HashSet<string>()).ToList();
var properties = GetProperties(cc.Members, new HashSet<string>()).ToList();

if (props.Any())
if (properties.Any())
{
var intellisenseObject = new IntellisenseObject
var intellisenseObject = new IntellisenseObject(properties)
{
Namespace = GetNamespace(cc),
Name = cc.Name,
FullName = cc.FullName,
Summary = GetSummary(cc),
};

intellisenseObject.Properties.AddRange(props);
list.Add(intellisenseObject);
}
}
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 c226c2d

Please sign in to comment.