FileSystemTreeBuilder.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #nullable disable
  2. using System.IO.Abstractions;
  3. namespace Terminal.Gui.FileServices;
  4. /// <summary>TreeView builder for creating file system based trees.</summary>
  5. public class FileSystemTreeBuilder : ITreeBuilder<IFileSystemInfo>, IComparer<IFileSystemInfo>
  6. {
  7. /// <summary>Creates a new instance of the <see cref="FileSystemTreeBuilder"/> class.</summary>
  8. public FileSystemTreeBuilder () { Sorter = this; }
  9. /// <summary>Gets or sets a flag indicating whether to show files as leaf elements in the tree. Defaults to true.</summary>
  10. public bool IncludeFiles { get; } = true;
  11. /// <summary>Gets or sets the order of directory children. Defaults to <see langword="this"/>.</summary>
  12. public IComparer<IFileSystemInfo> Sorter { get; set; }
  13. /// <inheritdoc/>
  14. public int Compare (IFileSystemInfo x, IFileSystemInfo y)
  15. {
  16. if (x is IDirectoryInfo && y is not IDirectoryInfo)
  17. {
  18. return -1;
  19. }
  20. if (x is not IDirectoryInfo && y is IDirectoryInfo)
  21. {
  22. return 1;
  23. }
  24. return x.Name.CompareTo (y.Name);
  25. }
  26. /// <inheritdoc/>
  27. public bool SupportsCanExpand => true;
  28. /// <inheritdoc/>
  29. public bool CanExpand (IFileSystemInfo toExpand) { return TryGetChildren (toExpand).Any (); }
  30. /// <inheritdoc/>
  31. public IEnumerable<IFileSystemInfo> GetChildren (IFileSystemInfo forObject) { return TryGetChildren (forObject).OrderBy (k => k, Sorter); }
  32. private IEnumerable<IFileSystemInfo> TryGetChildren (IFileSystemInfo entry)
  33. {
  34. if (entry is IFileInfo)
  35. {
  36. return Enumerable.Empty<IFileSystemInfo> ();
  37. }
  38. var dir = (IDirectoryInfo)entry;
  39. try
  40. {
  41. return dir.GetFileSystemInfos ().Where (e => IncludeFiles || e is IDirectoryInfo);
  42. }
  43. catch (Exception)
  44. {
  45. return Enumerable.Empty<IFileSystemInfo> ();
  46. }
  47. }
  48. }