-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
PhysicalFileProvider.cs
365 lines (323 loc) · 13.6 KB
/
PhysicalFileProvider.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using Microsoft.Extensions.FileProviders.Internal;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.Extensions.FileProviders.Physical.Internal;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Extensions.FileProviders
{
/// <summary>
/// Looks up files using the on-disk file system
/// </summary>
/// <remarks>
/// When the environment variable "DOTNET_USE_POLLING_FILE_WATCHER" is set to "1" or "true", calls to
/// <see cref="Watch(string)" /> will use <see cref="PollingFileChangeToken" />.
/// </remarks>
public class PhysicalFileProvider : IFileProvider, IDisposable
{
private const string PollingEnvironmentKey = "DOTNET_USE_POLLING_FILE_WATCHER";
private static readonly char[] _pathSeparators = new[]
{Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar};
private readonly ExclusionFilters _filters;
private readonly Func<PhysicalFilesWatcher> _fileWatcherFactory;
private PhysicalFilesWatcher? _fileWatcher;
private bool _fileWatcherInitialized;
private object _fileWatcherLock = new();
private bool? _usePollingFileWatcher;
private bool? _useActivePolling;
private bool _disposed;
/// <summary>
/// Initializes a new instance of a PhysicalFileProvider at the given root directory.
/// </summary>
/// <param name="root">The root directory. This should be an absolute path.</param>
public PhysicalFileProvider(string root)
: this(root, ExclusionFilters.Sensitive)
{
}
/// <summary>
/// Initializes a new instance of a PhysicalFileProvider at the given root directory.
/// </summary>
/// <param name="root">The root directory. This should be an absolute path.</param>
/// <param name="filters">Specifies which files or directories are excluded.</param>
public PhysicalFileProvider(string root, ExclusionFilters filters)
{
if (!Path.IsPathRooted(root))
{
throw new ArgumentException("The path must be absolute.", nameof(root));
}
string fullRoot = Path.GetFullPath(root);
// When we do matches in GetFullPath, we want to only match full directory names.
Root = PathUtils.EnsureTrailingSlash(fullRoot);
if (!Directory.Exists(Root))
{
throw new DirectoryNotFoundException(Root);
}
_filters = filters;
_fileWatcherFactory = () => CreateFileWatcher();
}
/// <summary>
/// Gets or sets a value that determines if this instance of <see cref="PhysicalFileProvider"/>
/// uses polling to determine file changes.
/// <para>
/// By default, <see cref="PhysicalFileProvider"/> uses <see cref="FileSystemWatcher"/> to listen to file change events
/// for <see cref="Watch(string)"/>. <see cref="FileSystemWatcher"/> is ineffective in some scenarios such as mounted drives.
/// Polling is required to effectively watch for file changes.
/// </para>
/// <seealso cref="UseActivePolling"/>.
/// </summary>
/// <value>
/// The default value of this property is determined by the value of environment variable named <c>DOTNET_USE_POLLING_FILE_WATCHER</c>.
/// When <c>true</c> or <c>1</c>, this property defaults to <c>true</c>; otherwise false.
/// </value>
public bool UsePollingFileWatcher
{
get
{
if (_fileWatcher != null)
{
return false;
}
if (_usePollingFileWatcher == null)
{
ReadPollingEnvironmentVariables();
}
return _usePollingFileWatcher ?? false;
}
set
{
if (_fileWatcher != null)
{
throw new InvalidOperationException(SR.Format(SR.CannotModifyWhenFileWatcherInitialized, nameof(UsePollingFileWatcher)));
}
_usePollingFileWatcher = value;
}
}
/// <summary>
/// Gets or sets a value that determines if this instance of <see cref="PhysicalFileProvider"/>
/// actively polls for file changes.
/// <para>
/// When <see langword="true"/>, <see cref="IChangeToken"/> returned by <see cref="Watch(string)"/> will actively poll for file changes
/// (<see cref="IChangeToken.ActiveChangeCallbacks"/> will be <see langword="true"/>) instead of being passive.
/// </para>
/// <para>
/// This property is only effective when <see cref="UsePollingFileWatcher"/> is set.
/// </para>
/// </summary>
/// <value>
/// The default value of this property is determined by the value of environment variable named <c>DOTNET_USE_POLLING_FILE_WATCHER</c>.
/// When <c>true</c> or <c>1</c>, this property defaults to <c>true</c>; otherwise false.
/// </value>
public bool UseActivePolling
{
get
{
if (_useActivePolling == null)
{
ReadPollingEnvironmentVariables();
}
return _useActivePolling.Value;
}
set => _useActivePolling = value;
}
internal PhysicalFilesWatcher FileWatcher
{
get
{
return LazyInitializer.EnsureInitialized(
ref _fileWatcher,
ref _fileWatcherInitialized,
ref _fileWatcherLock,
_fileWatcherFactory)!;
}
set
{
Debug.Assert(!_fileWatcherInitialized);
_fileWatcherInitialized = true;
_fileWatcher = value;
}
}
internal PhysicalFilesWatcher CreateFileWatcher()
{
string root = PathUtils.EnsureTrailingSlash(Path.GetFullPath(Root));
FileSystemWatcher? watcher;
#if NETCOREAPP
// For browser/iOS/tvOS we will proactively fallback to polling since FileSystemWatcher is not supported.
if (OperatingSystem.IsBrowser() || (OperatingSystem.IsIOS() && !OperatingSystem.IsMacCatalyst()) || OperatingSystem.IsTvOS())
{
UsePollingFileWatcher = true;
UseActivePolling = true;
watcher = null;
}
else
#endif
{
// When UsePollingFileWatcher & UseActivePolling are set, we won't use a FileSystemWatcher.
watcher = UsePollingFileWatcher && UseActivePolling ? null : new FileSystemWatcher(root);
}
return new PhysicalFilesWatcher(root, watcher, UsePollingFileWatcher, _filters)
{
UseActivePolling = UseActivePolling,
};
}
[MemberNotNull(nameof(_usePollingFileWatcher))]
[MemberNotNull(nameof(_useActivePolling))]
private void ReadPollingEnvironmentVariables()
{
string? environmentValue = Environment.GetEnvironmentVariable(PollingEnvironmentKey);
bool pollForChanges = string.Equals(environmentValue, "1", StringComparison.Ordinal) ||
string.Equals(environmentValue, "true", StringComparison.OrdinalIgnoreCase);
_usePollingFileWatcher = pollForChanges;
_useActivePolling = pollForChanges;
}
/// <summary>
/// Disposes the provider. Change tokens may not trigger after the provider is disposed.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the provider.
/// </summary>
/// <param name="disposing"><c>true</c> is invoked from <see cref="IDisposable.Dispose"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_fileWatcher?.Dispose();
}
_disposed = true;
}
}
/// <summary>
/// The root directory for this instance.
/// </summary>
public string Root { get; }
private string? GetFullPath(string path)
{
if (PathUtils.PathNavigatesAboveRoot(path))
{
return null;
}
string fullPath;
try
{
fullPath = Path.GetFullPath(Path.Combine(Root, path));
}
catch
{
return null;
}
if (!IsUnderneathRoot(fullPath))
{
return null;
}
return fullPath;
}
private bool IsUnderneathRoot(string fullPath)
{
return fullPath.StartsWith(Root, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Locate a file at the given path by directly mapping path segments to physical directories.
/// </summary>
/// <param name="subpath">A path under the root directory</param>
/// <returns>The file information. Caller must check <see cref="IFileInfo.Exists"/> property. </returns>
public IFileInfo GetFileInfo(string subpath)
{
if (string.IsNullOrEmpty(subpath) || PathUtils.HasInvalidPathChars(subpath))
{
return new NotFoundFileInfo(subpath);
}
// Relative paths starting with leading slashes are okay
subpath = subpath.TrimStart(_pathSeparators);
// Absolute paths not permitted.
if (Path.IsPathRooted(subpath))
{
return new NotFoundFileInfo(subpath);
}
string? fullPath = GetFullPath(subpath);
if (fullPath == null)
{
return new NotFoundFileInfo(subpath);
}
var fileInfo = new FileInfo(fullPath);
if (FileSystemInfoHelper.IsExcluded(fileInfo, _filters))
{
return new NotFoundFileInfo(subpath);
}
return new PhysicalFileInfo(fileInfo);
}
/// <summary>
/// Enumerate a directory at the given path, if any.
/// </summary>
/// <param name="subpath">A path under the root directory. Leading slashes are ignored.</param>
/// <returns>
/// Contents of the directory. Caller must check <see cref="IDirectoryContents.Exists"/> property. <see cref="NotFoundDirectoryContents" /> if
/// <paramref name="subpath" /> is absolute, if the directory does not exist, or <paramref name="subpath" /> has invalid
/// characters.
/// </returns>
public IDirectoryContents GetDirectoryContents(string subpath)
{
try
{
if (subpath == null || PathUtils.HasInvalidPathChars(subpath))
{
return NotFoundDirectoryContents.Singleton;
}
// Relative paths starting with leading slashes are okay
subpath = subpath.TrimStart(_pathSeparators);
// Absolute paths not permitted.
if (Path.IsPathRooted(subpath))
{
return NotFoundDirectoryContents.Singleton;
}
string? fullPath = GetFullPath(subpath);
if (fullPath == null || !Directory.Exists(fullPath))
{
return NotFoundDirectoryContents.Singleton;
}
return new PhysicalDirectoryContents(fullPath, _filters);
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
return NotFoundDirectoryContents.Singleton;
}
/// <summary>
/// <para>Creates a <see cref="IChangeToken" /> for the specified <paramref name="filter" />.</para>
/// <para>Globbing patterns are interpreted by <seealso cref="Microsoft.Extensions.FileSystemGlobbing.Matcher" />.</para>
/// </summary>
/// <param name="filter">
/// Filter string used to determine what files or folders to monitor. Example: **/*.cs, *.*,
/// subFolder/**/*.cshtml.
/// </param>
/// <returns>
/// An <see cref="IChangeToken" /> that is notified when a file matching <paramref name="filter" /> is added,
/// modified or deleted. Returns a <see cref="NullChangeToken" /> if <paramref name="filter" /> has invalid filter
/// characters or if <paramref name="filter" /> is an absolute path or outside the root directory specified in the
/// constructor <seealso cref="PhysicalFileProvider(string)" />.
/// </returns>
public IChangeToken Watch(string filter)
{
if (filter == null || PathUtils.HasInvalidFilterChars(filter))
{
return NullChangeToken.Singleton;
}
// Relative paths starting with leading slashes are okay
filter = filter.TrimStart(_pathSeparators);
return FileWatcher.CreateFileChangeToken(filter);
}
}
}