FileSystemTreeBuilder.cs 1.9 KB

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