This repository has been archived by the owner on Nov 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathPhysicalFilesWatcher.cs
235 lines (201 loc) · 8.01 KB
/
PhysicalFilesWatcher.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.FileSystemGlobbing.Abstractions;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Extensions.FileProviders.Physical
{
public class PhysicalFilesWatcher : IDisposable
{
private readonly ConcurrentDictionary<string, ChangeTokenInfo> _matchInfoCache =
new ConcurrentDictionary<string, ChangeTokenInfo>(StringComparer.OrdinalIgnoreCase);
private readonly FileSystemWatcher _fileWatcher;
private readonly object _lockObject = new object();
private readonly string _root;
private readonly bool _pollForChanges;
public PhysicalFilesWatcher(
string root,
FileSystemWatcher fileSystemWatcher,
bool pollForChanges)
{
_root = root;
_fileWatcher = fileSystemWatcher;
_fileWatcher.IncludeSubdirectories = true;
_fileWatcher.Created += OnChanged;
_fileWatcher.Changed += OnChanged;
_fileWatcher.Renamed += OnRenamed;
_fileWatcher.Deleted += OnChanged;
_fileWatcher.Error += OnError;
_pollForChanges = pollForChanges;
}
public IChangeToken CreateFileChangeToken(string filter)
{
if (filter == null)
{
throw new ArgumentNullException(nameof(filter));
}
filter = NormalizePath(filter);
IChangeToken changeToken;
var isWildCard = filter.IndexOf('*') != -1;
if (isWildCard || IsDirectoryPath(filter))
{
changeToken = ResolveFileTokensForGlobbingPattern(filter);
}
else
{
changeToken = GetOrAddChangeToken(filter);
}
lock (_lockObject)
{
if (_matchInfoCache.Count > 0 && !_fileWatcher.EnableRaisingEvents)
{
// Perf: Turn on the file monitoring if there is something to monitor.
_fileWatcher.EnableRaisingEvents = true;
}
}
return changeToken;
}
private IChangeToken GetOrAddChangeToken(string filePath)
{
ChangeTokenInfo tokenInfo;
if (!_matchInfoCache.TryGetValue(filePath, out tokenInfo))
{
var cancellationTokenSource = new CancellationTokenSource();
var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
tokenInfo = new ChangeTokenInfo(cancellationTokenSource, cancellationChangeToken);
tokenInfo = _matchInfoCache.GetOrAdd(filePath, tokenInfo);
}
IChangeToken changeToken = tokenInfo.ChangeToken;
if (_pollForChanges)
{
// The expiry of CancellationChangeToken is controlled by this type and consequently we can cache it.
// PollingFileChangeToken on the other hand manages its own lifetime and consequently we cannot cache it.
changeToken = new CompositeFileChangeToken(
new[]
{
changeToken,
new PollingFileChangeToken(new FileInfo(filePath))
});
}
return changeToken;
}
private IChangeToken ResolveFileTokensForGlobbingPattern(string filter)
{
var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);
matcher.AddInclude(filter);
var directoryBase = new DirectoryInfoWrapper(new DirectoryInfo(_root));
var result = matcher.Execute(directoryBase);
var changeTokens = new List<IChangeToken>();
foreach (var file in result.Files)
{
var changeToken = GetOrAddChangeToken(file.Path);
changeTokens.Add(changeToken);
}
return new CompositeFileChangeToken(changeTokens);
}
public void Dispose()
{
_fileWatcher.Dispose();
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
// For a file name change or a directory's name change notify registered tokens.
OnFileSystemEntryChange(e.OldFullPath);
OnFileSystemEntryChange(e.FullPath);
if (Directory.Exists(e.FullPath))
{
// If the renamed entity is a directory then notify tokens for every sub item.
foreach (var newLocation in Directory.EnumerateFileSystemEntries(e.FullPath, "*", SearchOption.AllDirectories))
{
// Calculated previous path of this moved item.
var oldLocation = Path.Combine(e.OldFullPath, newLocation.Substring(e.FullPath.Length + 1));
OnFileSystemEntryChange(oldLocation);
OnFileSystemEntryChange(newLocation);
}
}
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
OnFileSystemEntryChange(e.FullPath);
}
private void OnError(object sender, ErrorEventArgs e)
{
// Notify all cache entries on error.
foreach (var path in _matchInfoCache.Keys)
{
ReportChangeForMatchedEntries(path);
}
}
private void OnFileSystemEntryChange(string fullPath)
{
var fileSystemInfo = new FileInfo(fullPath);
if (FileSystemInfoHelper.IsHiddenFile(fileSystemInfo))
{
return;
}
var relativePath = fullPath.Substring(_root.Length);
ReportChangeForMatchedEntries(relativePath);
}
private void ReportChangeForMatchedEntries(string path)
{
path = NormalizePath(path);
ChangeTokenInfo matchInfo;
if (_matchInfoCache.TryRemove(path, out matchInfo))
{
CancelToken(matchInfo);
if (_matchInfoCache.Count == 0)
{
lock (_lockObject)
{
if (_matchInfoCache.Count == 0 && _fileWatcher.EnableRaisingEvents)
{
// Perf: Turn off the file monitoring if no files to monitor.
_fileWatcher.EnableRaisingEvents = false;
}
}
}
}
}
private static string NormalizePath(string filter) => filter = filter.Replace('\\', '/');
private static bool IsDirectoryPath(string path)
{
return path.Length > 0
&& (path[path.Length - 1] == Path.DirectorySeparatorChar || path[path.Length - 1] == Path.AltDirectorySeparatorChar);
}
private static void CancelToken(ChangeTokenInfo matchInfo)
{
if (matchInfo.TokenSource.IsCancellationRequested)
{
return;
}
Task.Run(() =>
{
try
{
matchInfo.TokenSource.Cancel();
}
catch
{
}
});
}
private struct ChangeTokenInfo
{
public ChangeTokenInfo(
CancellationTokenSource tokenSource,
CancellationChangeToken changeToken)
{
TokenSource = tokenSource;
ChangeToken = changeToken;
}
public CancellationTokenSource TokenSource { get; }
public CancellationChangeToken ChangeToken { get; }
}
}
}