DotIgnoreIgnoreRule.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. if (fileInfo.IsDirectory)
  40. {
  41. var dirIgnoreFile = FindIgnoreFile(new DirectoryInfo(fileInfo.FullName));
  42. if (dirIgnoreFile is null)
  43. {
  44. return false;
  45. }
  46. // ignore the directory only if the .ignore file is empty
  47. // evaluate individual files otherwise
  48. return string.IsNullOrWhiteSpace(GetFileContent(dirIgnoreFile));
  49. }
  50. var parentDirPath = Path.GetDirectoryName(fileInfo.FullName);
  51. if (string.IsNullOrEmpty(parentDirPath))
  52. {
  53. return false;
  54. }
  55. var folder = new DirectoryInfo(parentDirPath);
  56. var ignoreFile = FindIgnoreFile(folder);
  57. if (ignoreFile is null)
  58. {
  59. return false;
  60. }
  61. string ignoreFileString = GetFileContent(ignoreFile);
  62. if (string.IsNullOrWhiteSpace(ignoreFileString))
  63. {
  64. // Ignore directory if we just have the file
  65. return true;
  66. }
  67. // If file has content, base ignoring off the content .gitignore-style rules
  68. var ignoreRules = ignoreFileString.Split('\n', StringSplitOptions.RemoveEmptyEntries);
  69. var ignore = new Ignore.Ignore();
  70. ignore.Add(ignoreRules);
  71. return ignore.IsIgnored(fileInfo.FullName);
  72. }
  73. private static string GetFileContent(FileInfo dirIgnoreFile)
  74. {
  75. using (var reader = dirIgnoreFile.OpenText())
  76. {
  77. return reader.ReadToEnd();
  78. }
  79. }
  80. }