DotIgnoreIgnoreRule.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.IO;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Resolvers;
  5. using MediaBrowser.Model.IO;
  6. namespace Emby.Server.Implementations.Library;
  7. /// <summary>
  8. /// Resolver rule class for ignoring files via .ignore.
  9. /// </summary>
  10. public class DotIgnoreIgnoreRule : IResolverIgnoreRule
  11. {
  12. private static FileInfo? FindIgnoreFile(DirectoryInfo directory)
  13. {
  14. var ignoreFile = new FileInfo(Path.Join(directory.FullName, ".ignore"));
  15. if (ignoreFile.Exists)
  16. {
  17. return ignoreFile;
  18. }
  19. var parentDir = directory.Parent;
  20. if (parentDir is null)
  21. {
  22. return null;
  23. }
  24. return FindIgnoreFile(parentDir);
  25. }
  26. /// <inheritdoc />
  27. public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem? parent)
  28. {
  29. return IsIgnored(fileInfo, parent);
  30. }
  31. /// <summary>
  32. /// Checks whether or not the file is ignored.
  33. /// </summary>
  34. /// <param name="fileInfo">The file information.</param>
  35. /// <param name="parent">The parent BaseItem.</param>
  36. /// <returns>True if the file should be ignored.</returns>
  37. public static bool IsIgnored(FileSystemMetadata fileInfo, BaseItem? parent)
  38. {
  39. var parentDirPath = Path.GetDirectoryName(fileInfo.FullName);
  40. if (string.IsNullOrEmpty(parentDirPath))
  41. {
  42. return false;
  43. }
  44. var folder = new DirectoryInfo(parentDirPath);
  45. var ignoreFile = FindIgnoreFile(folder);
  46. if (ignoreFile is null)
  47. {
  48. return false;
  49. }
  50. string ignoreFileString;
  51. using (var reader = ignoreFile.OpenText())
  52. {
  53. ignoreFileString = reader.ReadToEnd();
  54. }
  55. if (string.IsNullOrEmpty(ignoreFileString))
  56. {
  57. // Ignore directory if we just have the file
  58. return true;
  59. }
  60. // If file has content, base ignoring off the content .gitignore-style rules
  61. var ignoreRules = ignoreFileString.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  62. var ignore = new Ignore.Ignore();
  63. ignore.Add(ignoreRules);
  64. return ignore.IsIgnored(fileInfo.FullName);
  65. }
  66. }