FileSystemTreeBuilder.cs 1.9 KB

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