/
IgnoreHashFileProvider.cs
94 lines (74 loc) · 2.67 KB
/
IgnoreHashFileProvider.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
89
90
91
92
93
94
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Text.RegularExpressions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace Squidex.Web;
public sealed class IgnoreHashFileProvider : IFileProvider
{
private readonly char[] pathSeparators = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, '\\' };
private readonly Dictionary<string, string> map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private readonly IFileProvider inner;
public IgnoreHashFileProvider(IFileProvider inner)
{
this.inner = inner;
var regex = new Regex("^(?<Name>[^.]+)\\.[0-9a-f]{4,}\\.(?<Extension>.+)$");
void MapDirectory(string path)
{
foreach (var file in inner.GetDirectoryContents(path))
{
if (file.IsDirectory)
{
MapDirectory(Combine(path, file.Name));
continue;
}
var match = regex.Match(file.Name);
if (match.Success)
{
var nameWithouthHash = $"{match.Groups["Name"].Value}.{match.Groups["Extension"].Value}";
var pathHashed = Combine(path, file.Name);
var pathNormal = Combine(path, nameWithouthHash);
map[pathNormal] = pathHashed;
}
}
}
MapDirectory(string.Empty);
}
public IFileInfo GetFileInfo(string subpath)
{
var file = inner.GetFileInfo(subpath);
if (!file.Exists)
{
subpath = subpath.TrimStart(pathSeparators).Replace('\\', '/');
if (map.TryGetValue(subpath, out var withHash))
{
file = inner.GetFileInfo(withHash);
}
}
return file;
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
return inner.GetDirectoryContents(subpath);
}
public IChangeToken Watch(string filter)
{
return inner.Watch(filter);
}
private static string Combine(string path1, string path2)
{
if (string.IsNullOrWhiteSpace(path1))
{
return path2;
}
if (string.IsNullOrWhiteSpace(path2))
{
return path1;
}
return $"{path1}/{path2}";
}
}