Skip to content
0.2.0-dev Download ZIP
272 lines ·8.4 KB Raw
1using System.Diagnostics.CodeAnalysis;
2using System.IO.Enumeration;
3
4namespace EvilEngine.Mounts;
5
6public sealed class FolderSource : IFileSource, IDisposable
7{
8 private static readonly EnumerationOptions Options = new() { IgnoreInaccessible = true, AttributesToSkip = 0 };
9
10 private readonly Folder _root;
11 private readonly bool _shallow;
12 private int _disposed;
13
14 public FolderSource(string root, CaseRule caseRule, bool shallow = false)
15 {
16 Location = Path.GetFullPath(root);
17 CaseRule = caseRule;
18 _shallow = shallow;
19 _root = new Folder(this, VirtualPath.Root, Real(new DirectoryInfo(Location)) is { } real
20 ? [new Place(Location, real, new Above(real, null))]
21 : []);
22 }
23
24 public int Count => EnumerateAll().Count();
25
26 public bool IsDisposed => _disposed != 0;
27
28 public void Dispose()
29 {
30 Interlocked.Exchange(ref _disposed, 1);
31 }
32
33 public string Location { get; }
34
35 public CaseRule CaseRule { get; }
36
37 public bool Exists(VirtualPath path)
38 {
39 return File(path) is not null;
40 }
41
42 public bool TryOpen(VirtualPath path, [NotNullWhen(true)] out Stream? stream)
43 {
44 ObjectDisposedException.ThrowIf(IsDisposed, this);
45 stream = null;
46 if (File(path) is not { } file)
47 return false;
48 try
49 {
50 stream = new FileStream(file.Host, FileMode.Open, FileAccess.Read, FileShare.Read);
51 }
52 catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
53 {
54 }
55
56 return stream is not null;
57 }
58
59 public bool TryOpenAccess(VirtualPath path, [NotNullWhen(true)] out IRandomAccess? access)
60 {
61 ObjectDisposedException.ThrowIf(IsDisposed, this);
62 access = null;
63 if (File(path) is not { } file)
64 return false;
65 try
66 {
67 access = new HostFile(file.Host);
68 }
69 catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException)
70 {
71 }
72
73 return access is not null;
74 }
75
76 public IEnumerable<FileEntry> Enumerate(VirtualPath directory, bool recursive)
77 {
78 if (Find(directory) is not { } folder)
79 return [];
80 if (!recursive)
81 return folder.Listing.Files.Select(file => file.Entry);
82 folder.Prefetch();
83 return Walk(folder);
84 }
85
86 public bool DirectoryExists(VirtualPath directory)
87 {
88 return Find(directory) is not null;
89 }
90
91 public IEnumerable<VirtualPath> EnumerateDirectories(VirtualPath directory)
92 {
93 return Find(directory) is { } folder ? folder.Listing.Folders.Select(child => child.Path) : [];
94 }
95
96 public IEnumerable<FileEntry> EnumerateAll()
97 {
98 return Enumerate(VirtualPath.Root, true);
99 }
100
101 private static IEnumerable<FileEntry> Walk(Folder top)
102 {
103 var pending = new Stack<Folder>();
104 pending.Push(top);
105 while (pending.TryPop(out var folder))
106 {
107 var listing = folder.Listing;
108 foreach (var file in listing.Files)
109 yield return file.Entry;
110 for (var i = listing.Folders.Count - 1; i >= 0; i--)
111 pending.Push(listing.Folders[i]);
112 }
113 }
114
115 private Folder? Find(VirtualPath directory)
116 {
117 var folder = _root;
118 if (directory.IsRoot)
119 return folder;
120 foreach (var name in directory.Value.Split(VirtualPath.Separator))
121 if (!folder.Listing.ByName.TryGetValue(name, out folder))
122 return null;
123 return folder;
124 }
125
126 private HostEntry? File(VirtualPath path)
127 {
128 return !path.IsRoot && Find(path.Parent) is { } folder &&
129 folder.Listing.FilesByName.TryGetValue(path.Name, out var file)
130 ? file
131 : null;
132 }
133
134 private Listing List(Folder folder)
135 {
136 var comparer = VirtualPath.Comparer(CaseRule);
137 var files = new List<HostEntry>();
138 var filesByName = new Dictionary<string, HostEntry>(comparer);
139 var children = new List<Folder>();
140 var byName = new Dictionary<string, Folder>(comparer);
141 foreach (var place in folder.Places)
142 foreach (var (name, full, length, directory, link) in Entries(place.Host))
143 {
144 if (!VirtualPath.TryParse(folder.Path.IsRoot ? name : $"{folder.Path.Value}/{name}", out var path) ||
145 path.Parent != folder.Path)
146 continue;
147 if (!directory)
148 {
149 if (filesByName.TryAdd(path.Name, new HostEntry(new FileEntry(path, length), full)))
150 files.Add(filesByName[path.Name]);
151 continue;
152 }
153
154 if (_shallow)
155 continue;
156 var real = link ?? Path.Combine(place.Real, name);
157 if (place.Above.Holds(real))
158 continue;
159 var at = new Place(full, real, new Above(real, place.Above));
160 if (byName.TryGetValue(path.Name, out var twin))
161 {
162 twin.Places.Add(at);
163 continue;
164 }
165
166 var child = new Folder(this, path, [at]);
167 byName.Add(path.Name, child);
168 children.Add(child);
169 }
170
171 return new Listing(files, filesByName, children, byName);
172 }
173
174 private static IEnumerable<(string Name, string Full, long Length, bool Directory, string? Link)> Entries(
175 string host)
176 {
177 IEnumerable<(string Name, string Full, long Length, bool Directory, bool Link)> raw;
178 try
179 {
180 raw = new FileSystemEnumerable<(string, string, long, bool, bool)>(host,
181 (ref entry) => (entry.FileName.ToString(), entry.ToFullPath(),
182 entry.IsDirectory ? 0 : entry.Length, entry.IsDirectory,
183 entry.Attributes.HasFlag(FileAttributes.ReparsePoint)), Options).ToList();
184 }
185 catch (Exception error) when (error is DirectoryNotFoundException or IOException or UnauthorizedAccessException)
186 {
187 yield break;
188 }
189
190 foreach (var (name, full, length, directory, link) in raw)
191 {
192 if (!link)
193 {
194 yield return (name, full, length, directory, null);
195 continue;
196 }
197
198 var target = Target(Directory.Exists(full) ? new DirectoryInfo(full) : new FileInfo(full));
199 if (target is FileInfo file)
200 yield return (name, full, file.Length, false, null);
201 else if (target is DirectoryInfo)
202 yield return (name, full, 0, true, target.FullName);
203 }
204 }
205
206 private static FileSystemInfo? Target(FileSystemInfo entry)
207 {
208 if (!entry.Attributes.HasFlag(FileAttributes.ReparsePoint))
209 return entry.Exists ? entry : null;
210 try
211 {
212 return entry.ResolveLinkTarget(true) is { Exists: true } target ? target : null;
213 }
214 catch (IOException)
215 {
216 return null;
217 }
218 }
219
220 private static string? Real(DirectoryInfo directory)
221 {
222 return directory.Exists ? Target(directory)?.FullName : null;
223 }
224
225 private sealed record HostEntry(FileEntry Entry, string Host);
226
227 private sealed record Place(string Host, string Real, Above Above);
228
229 private sealed record Above(string Real, Above? Parent)
230 {
231 public bool Holds(string real)
232 {
233 for (var above = this; above != null; above = above.Parent)
234 if (above.Real == real)
235 return true;
236 return false;
237 }
238 }
239
240 private sealed record Listing(
241 List<HostEntry> Files,
242 Dictionary<string, HostEntry> FilesByName,
243 List<Folder> Folders,
244 Dictionary<string, Folder> ByName);
245
246 private sealed class Folder
247 {
248 private readonly Lazy<Listing> _listing;
249
250 public Folder(FolderSource owner, VirtualPath path, List<Place> places)
251 {
252 Path = path;
253 Places = places;
254 _listing = new Lazy<Listing>(() => owner.List(this));
255 }
256
257 public VirtualPath Path { get; }
258
259 public List<Place> Places { get; }
260
261 public Listing Listing => _listing.Value;
262
263 public void Prefetch()
264 {
265 var folders = Listing.Folders;
266 if (folders.Count == 1)
267 folders[0].Prefetch();
268 else if (folders.Count > 1)
269 Parallel.ForEach(folders, folder => folder.Prefetch());
270 }
271 }
272}