forked from dotless/dotless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheDecorator.cs
72 lines (61 loc) · 2.08 KB
/
CacheDecorator.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
namespace dotless.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Cache;
using Loggers;
public class CacheDecorator : ILessEngine
{
public readonly ILessEngine Underlying;
public readonly ICache Cache;
public ILogger Logger { get; set; }
public CacheDecorator(ILessEngine underlying, ICache cache) : this(underlying, cache, NullLogger.Instance)
{}
public CacheDecorator(ILessEngine underlying, ICache cache, ILogger logger)
{
Underlying = underlying;
Cache = cache;
Logger = logger;
}
public string TransformToCss(string source, string fileName)
{
//Compute Cache Key
var hash = ComputeContentHash(source);
var cacheKey = fileName + hash;
if (!Cache.Exists(cacheKey))
{
Logger.Debug(String.Format("Inserting cache entry for {0}", cacheKey));
var css = Underlying.TransformToCss(source, fileName);
var dependancies = new[] { fileName }.Concat(GetImports());
Cache.Insert(cacheKey, dependancies, css);
return css;
}
Logger.Debug(String.Format("Retrieving cache entry {0}", cacheKey));
return Cache.Retrieve(cacheKey);
}
private string ComputeContentHash(string source)
{
SHA1 sha1 = SHA1.Create();
byte[] computeHash = sha1.ComputeHash(Encoding.Default.GetBytes(source));
return Convert.ToBase64String(computeHash);
}
public IEnumerable<string> GetImports()
{
return Underlying.GetImports();
}
public void ResetImports()
{
Underlying.ResetImports();
}
public bool LastTransformationSuccessful
{
get
{
return Underlying.LastTransformationSuccessful;
}
}
}
}