-
Notifications
You must be signed in to change notification settings - Fork 368
/
FileProvider.cs
91 lines (76 loc) · 2.8 KB
/
FileProvider.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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using Microsoft.DotNet.Interactive.Events;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace Microsoft.DotNet.Interactive.Http;
public class FileProvider : IFileProvider, IDisposable
{
private readonly EmbeddedFileProvider _root;
private readonly IDisposable _eventSubscription;
private readonly ConcurrentDictionary<string, EmbeddedFileProvider> _providers = new ConcurrentDictionary<string, EmbeddedFileProvider>();
public FileProvider(Kernel kernel, Assembly rootProviderAssembly)
{
if (kernel is null) throw new ArgumentNullException(nameof(kernel));
_root = new EmbeddedFileProvider(rootProviderAssembly ?? typeof(FileProvider).Assembly);
_eventSubscription = kernel.KernelEvents
.OfType<KernelExtensionLoaded>()
.Subscribe(@event => RegisterExtension(@event.KernelExtension));
}
private void RegisterExtension(IKernelExtension kernelExtension)
{
if (kernelExtension is IStaticContentSource source)
{
var name = source.Name;
_providers.GetOrAdd(name, key => new EmbeddedFileProvider(source.GetType().Assembly));
}
}
public IFileInfo GetFileInfo(string subpath)
{
var (provider, path) = GetProviderAndPath(subpath);
return provider.GetFileInfo(path);
}
private (IFileProvider provider, string path) GetProviderAndPath(string subpath)
{
IFileProvider provider = _root;
var path = subpath;
var parts = subpath.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
if (parts[0] == "extensions")
{
provider = SelectProvider();
path = ProcessPath();
}
return (provider, path);
string ProcessPath()
{
return string.Join("/", parts.Skip(2));
}
IFileProvider SelectProvider()
{
var name = parts[1];
if (!_providers.TryGetValue(name, out var embeddedFileProvider))
{
throw new StaticContentSourceNotFoundException(name);
}
return embeddedFileProvider;
}
}
public IDirectoryContents GetDirectoryContents(string subpath)
{
var (provider, path) = GetProviderAndPath(subpath);
return provider.GetDirectoryContents(path);
}
public IChangeToken Watch(string filter)
{
return NullChangeToken.Singleton;
}
public void Dispose()
{
_eventSubscription.Dispose();
}
}