using System.IO.Abstractions; namespace Terminal.Gui; /// TreeView builder for creating file system based trees. public class FileSystemTreeBuilder : ITreeBuilder, IComparer { /// Creates a new instance of the class. public FileSystemTreeBuilder () { Sorter = this; } /// Gets or sets a flag indicating whether to show files as leaf elements in the tree. Defaults to true. public bool IncludeFiles { get; } = true; /// Gets or sets the order of directory children. Defaults to . public IComparer Sorter { get; set; } /// public int Compare (IFileSystemInfo x, IFileSystemInfo y) { if (x is IDirectoryInfo && y is not IDirectoryInfo) { return -1; } if (x is not IDirectoryInfo && y is IDirectoryInfo) { return 1; } return x.Name.CompareTo (y.Name); } /// public bool SupportsCanExpand => true; /// public bool CanExpand (IFileSystemInfo toExpand) { return TryGetChildren (toExpand).Any (); } /// public IEnumerable GetChildren (IFileSystemInfo forObject) { return TryGetChildren (forObject).OrderBy (k => k, Sorter); } private IEnumerable TryGetChildren (IFileSystemInfo entry) { if (entry is IFileInfo) { return Enumerable.Empty (); } var dir = (IDirectoryInfo)entry; try { return dir.GetFileSystemInfos ().Where (e => IncludeFiles || e is IDirectoryInfo); } catch (Exception) { return Enumerable.Empty (); } } }