-
Notifications
You must be signed in to change notification settings - Fork 3
/
LessTransform.cs
88 lines (71 loc) · 2.67 KB
/
LessTransform.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Optimization;
using Web.Optimization.Common;
using dotless.Core.configuration;
namespace Web.Optimization.Bundles.Less
{
public class LessTransform : IBundleTransform
{
private readonly DotlessConfiguration _configuration;
public LessTransform(DotlessConfiguration configuration)
{
_configuration = configuration;
}
public LessTransform()
: this(DotlessConfiguration.GetDefaultWeb())
{ }
public void Process(BundleContext context, BundleResponse response)
{
var builder = new StringBuilder();
foreach (var file in response.Files)
{
var path =
context.HttpContext.Server.MapPath(
file.IncludedVirtualPath);
var fileInfo = new FileInfo(path);
if (!fileInfo.Exists)
{
continue;
}
var content = ResolveImports(fileInfo);
builder.AppendLine(
_configuration.Web
? dotless.Core.LessWeb.Parse(content, _configuration)
: dotless.Core.Less.Parse(content, _configuration));
}
response.ContentType = ContentType.Css;
response.Content = builder.ToString();
}
private static readonly Regex s_lessImportRegex =
new Regex("@import [\"|'](.+)[\"|'];", RegexOptions.Compiled);
private static string ResolveImports(FileInfo file)
{
var content = File.ReadAllText(file.FullName, Encoding.UTF8);
return s_lessImportRegex.Replace(
content,
match =>
{
var import = match.Groups[1].Value;
// Is absolute path?
Uri uri;
if (Uri.TryCreate(import, UriKind.Absolute, out uri))
{
return match.Value;
}
var path =
Path.Combine(
file.Directory.FullName,
import);
if (!File.Exists(path))
{
throw new ApplicationException(
string.Concat("Unable to resolve import ", import));
}
return match.Value.Replace(import, path);
});
}
}
}