using System.Diagnostics.CodeAnalysis; using System.IO.Enumeration; namespace EvilEngine.Mounts; public sealed class FolderSource : IFileSource, IDisposable { private static readonly EnumerationOptions Options = new() { IgnoreInaccessible = true, AttributesToSkip = 0 }; private readonly Folder _root; private readonly bool _shallow; private int _disposed; public FolderSource(string root, CaseRule caseRule, bool shallow = false) { Location = Path.GetFullPath(root); CaseRule = caseRule; _shallow = shallow; _root = new Folder(this, VirtualPath.Root, Real(new DirectoryInfo(Location)) is { } real ? [new Place(Location, real, new Above(real, null))] : []); } public int Count => EnumerateAll().Count(); public bool IsDisposed => _disposed != 0; public void Dispose() { Interlocked.Exchange(ref _disposed, 1); } public string Location { get; } public CaseRule CaseRule { get; } public bool Exists(VirtualPath path) { return File(path) is not null; } public bool TryOpen(VirtualPath path, [NotNullWhen(true)] out Stream? stream) { ObjectDisposedException.ThrowIf(IsDisposed, this); stream = null; if (File(path) is not { } file) return false; try { stream = new FileStream(file.Host, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException) { } return stream is not null; } public bool TryOpenAccess(VirtualPath path, [NotNullWhen(true)] out IRandomAccess? access) { ObjectDisposedException.ThrowIf(IsDisposed, this); access = null; if (File(path) is not { } file) return false; try { access = new HostFile(file.Host); } catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException) { } return access is not null; } public IEnumerable Enumerate(VirtualPath directory, bool recursive) { if (Find(directory) is not { } folder) return []; if (!recursive) return folder.Listing.Files.Select(file => file.Entry); folder.Prefetch(); return Walk(folder); } public bool DirectoryExists(VirtualPath directory) { return Find(directory) is not null; } public IEnumerable EnumerateDirectories(VirtualPath directory) { return Find(directory) is { } folder ? folder.Listing.Folders.Select(child => child.Path) : []; } public IEnumerable EnumerateAll() { return Enumerate(VirtualPath.Root, true); } private static IEnumerable Walk(Folder top) { var pending = new Stack(); pending.Push(top); while (pending.TryPop(out var folder)) { var listing = folder.Listing; foreach (var file in listing.Files) yield return file.Entry; for (var i = listing.Folders.Count - 1; i >= 0; i--) pending.Push(listing.Folders[i]); } } private Folder? Find(VirtualPath directory) { var folder = _root; if (directory.IsRoot) return folder; foreach (var name in directory.Value.Split(VirtualPath.Separator)) if (!folder.Listing.ByName.TryGetValue(name, out folder)) return null; return folder; } private HostEntry? File(VirtualPath path) { return !path.IsRoot && Find(path.Parent) is { } folder && folder.Listing.FilesByName.TryGetValue(path.Name, out var file) ? file : null; } private Listing List(Folder folder) { var comparer = VirtualPath.Comparer(CaseRule); var files = new List(); var filesByName = new Dictionary(comparer); var children = new List(); var byName = new Dictionary(comparer); foreach (var place in folder.Places) foreach (var (name, full, length, directory, link) in Entries(place.Host)) { if (!VirtualPath.TryParse(folder.Path.IsRoot ? name : $"{folder.Path.Value}/{name}", out var path) || path.Parent != folder.Path) continue; if (!directory) { if (filesByName.TryAdd(path.Name, new HostEntry(new FileEntry(path, length), full))) files.Add(filesByName[path.Name]); continue; } if (_shallow) continue; var real = link ?? Path.Combine(place.Real, name); if (place.Above.Holds(real)) continue; var at = new Place(full, real, new Above(real, place.Above)); if (byName.TryGetValue(path.Name, out var twin)) { twin.Places.Add(at); continue; } var child = new Folder(this, path, [at]); byName.Add(path.Name, child); children.Add(child); } return new Listing(files, filesByName, children, byName); } private static IEnumerable<(string Name, string Full, long Length, bool Directory, string? Link)> Entries( string host) { IEnumerable<(string Name, string Full, long Length, bool Directory, bool Link)> raw; try { raw = new FileSystemEnumerable<(string, string, long, bool, bool)>(host, (ref entry) => (entry.FileName.ToString(), entry.ToFullPath(), entry.IsDirectory ? 0 : entry.Length, entry.IsDirectory, entry.Attributes.HasFlag(FileAttributes.ReparsePoint)), Options).ToList(); } catch (Exception error) when (error is DirectoryNotFoundException or IOException or UnauthorizedAccessException) { yield break; } foreach (var (name, full, length, directory, link) in raw) { if (!link) { yield return (name, full, length, directory, null); continue; } var target = Target(Directory.Exists(full) ? new DirectoryInfo(full) : new FileInfo(full)); if (target is FileInfo file) yield return (name, full, file.Length, false, null); else if (target is DirectoryInfo) yield return (name, full, 0, true, target.FullName); } } private static FileSystemInfo? Target(FileSystemInfo entry) { if (!entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) return entry.Exists ? entry : null; try { return entry.ResolveLinkTarget(true) is { Exists: true } target ? target : null; } catch (IOException) { return null; } } private static string? Real(DirectoryInfo directory) { return directory.Exists ? Target(directory)?.FullName : null; } private sealed record HostEntry(FileEntry Entry, string Host); private sealed record Place(string Host, string Real, Above Above); private sealed record Above(string Real, Above? Parent) { public bool Holds(string real) { for (var above = this; above != null; above = above.Parent) if (above.Real == real) return true; return false; } } private sealed record Listing( List Files, Dictionary FilesByName, List Folders, Dictionary ByName); private sealed class Folder { private readonly Lazy _listing; public Folder(FolderSource owner, VirtualPath path, List places) { Path = path; Places = places; _listing = new Lazy(() => owner.List(this)); } public VirtualPath Path { get; } public List Places { get; } public Listing Listing => _listing.Value; public void Prefetch() { var folders = Listing.Folders; if (folders.Count == 1) folders[0].Prefetch(); else if (folders.Count > 1) Parallel.ForEach(folders, folder => folder.Prefetch()); } } }