aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs
blob: 023c1e891532e5baa022ef0e48b7179e991f59e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using BitFaster.Caching.Lru;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Resolvers;
using MediaBrowser.Model.IO;

namespace Emby.Server.Implementations.Library;

/// <summary>
/// Resolver rule class for ignoring files via .ignore.
/// </summary>
public class DotIgnoreIgnoreRule : IResolverIgnoreRule
{
    private static readonly bool IsWindows = OperatingSystem.IsWindows();

    private readonly FastConcurrentLru<string, IgnoreFileCacheEntry> _directoryCache;
    private readonly FastConcurrentLru<string, ParsedIgnoreCacheEntry> _rulesCache;

    /// <summary>
    /// Initializes a new instance of the <see cref="DotIgnoreIgnoreRule"/> class.
    /// </summary>
    public DotIgnoreIgnoreRule()
    {
        var cacheSize = Math.Max(100, Environment.ProcessorCount * 100);
        _directoryCache = new FastConcurrentLru<string, IgnoreFileCacheEntry>(
            Environment.ProcessorCount,
            cacheSize,
            StringComparer.Ordinal);
        _rulesCache = new FastConcurrentLru<string, ParsedIgnoreCacheEntry>(
            Environment.ProcessorCount,
            Math.Max(32, cacheSize / 4),
            StringComparer.Ordinal);
    }

    /// <inheritdoc />
    public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem? parent) => IsIgnoredInternal(fileInfo, parent);

    /// <summary>
    /// Clears the directory lookup cache. The parsed rules cache is not cleared
    /// as it validates file modification time on each access.
    /// </summary>
    public void ClearDirectoryCache()
    {
        _directoryCache.Clear();
    }

    /// <summary>
    /// Checks whether or not the file is ignored.
    /// </summary>
    /// <param name="fileInfo">The file information.</param>
    /// <param name="parent">The parent BaseItem.</param>
    /// <returns>True if the file should be ignored.</returns>
    public bool IsIgnoredInternal(FileSystemMetadata fileInfo, BaseItem? parent)
    {
        var searchDirectory = fileInfo.IsDirectory
            ? fileInfo.FullName
            : Path.GetDirectoryName(fileInfo.FullName);

        if (string.IsNullOrEmpty(searchDirectory))
        {
            return false;
        }

        var ignoreFile = FindIgnoreFileCached(searchDirectory);
        if (ignoreFile is null)
        {
            return false;
        }

        var parsedEntry = GetParsedRules(ignoreFile);
        if (parsedEntry is null)
        {
            // File was deleted after we cached the path - clear the directory cache entry and return false
            _directoryCache.TryRemove(searchDirectory, out _);
            return false;
        }

        // Empty file means ignore everything
        if (parsedEntry.IsEmpty)
        {
            return true;
        }

        return parsedEntry.Rules.IsIgnored(GetPathToCheck(fileInfo.FullName, fileInfo.IsDirectory));
    }

    /// <summary>
    /// Checks whether a path should be ignored based on an array of ignore rules.
    /// </summary>
    /// <param name="path">The path to check.</param>
    /// <param name="rules">The array of ignore rules.</param>
    /// <param name="isDirectory">Whether the path is a directory.</param>
    /// <returns>True if the path should be ignored.</returns>
    internal static bool CheckIgnoreRules(string path, string[] rules, bool isDirectory)
        => CheckIgnoreRules(path, rules, isDirectory, IsWindows);

    /// <summary>
    /// Checks whether a path should be ignored based on an array of ignore rules.
    /// </summary>
    /// <param name="path">The path to check.</param>
    /// <param name="rules">The array of ignore rules.</param>
    /// <param name="isDirectory">Whether the path is a directory.</param>
    /// <param name="normalizePath">Whether to normalize backslashes to forward slashes (for Windows paths).</param>
    /// <returns>True if the path should be ignored.</returns>
    internal static bool CheckIgnoreRules(string path, string[] rules, bool isDirectory, bool normalizePath)
    {
        var ignore = new Ignore.Ignore();

        // Add each rule individually to catch and skip invalid patterns
        var validRulesAdded = 0;
        foreach (var rule in rules)
        {
            try
            {
                ignore.Add(rule);
                validRulesAdded++;
            }
            catch (RegexParseException)
            {
                // Ignore invalid patterns
            }
        }

        // If no valid rules were added, fall back to ignoring everything (like an empty .ignore file)
        if (validRulesAdded == 0)
        {
            return true;
        }

        // Mitigate the problem of the Ignore library not handling Windows paths correctly.
        // See https://github.com/jellyfin/jellyfin/issues/15484
        var pathToCheck = normalizePath ? path.NormalizePath('/') : path;

        // Add trailing slash for directories to match "folder/"
        if (isDirectory)
        {
            pathToCheck = string.Concat(pathToCheck.AsSpan().TrimEnd('/'), "/");
        }

        return ignore.IsIgnored(pathToCheck);
    }

    private FileInfo? FindIgnoreFileCached(string directory)
    {
        // Check if we have a cached result for this directory
        if (_directoryCache.TryGet(directory, out var cached))
        {
            return cached.IgnoreFileDirectory is null
                ? null
                : new FileInfo(Path.Join(cached.IgnoreFileDirectory, ".ignore"));
        }

        DirectoryInfo startDir;
        try
        {
            startDir = new DirectoryInfo(directory);
        }
        catch (ArgumentException)
        {
            return null;
        }

        // Walk up the directory tree to find .ignore file using DirectoryInfo.Parent
        var checkedDirs = new List<string> { directory };

        for (var current = startDir; current is not null; current = current.Parent)
        {
            var currentPath = current.FullName;

            // Check if this intermediate directory is cached
            if (current != startDir && _directoryCache.TryGet(currentPath, out var parentCached))
            {
                // Cache the result for all directories we checked
                var entry = new IgnoreFileCacheEntry(parentCached.IgnoreFileDirectory);
                foreach (var dir in checkedDirs)
                {
                    _directoryCache.AddOrUpdate(dir, entry);
                }

                return parentCached.IgnoreFileDirectory is null
                    ? null
                    : new FileInfo(Path.Join(parentCached.IgnoreFileDirectory, ".ignore"));
            }

            var ignoreFile = new FileInfo(Path.Join(currentPath, ".ignore"));
            if (ignoreFile.Exists)
            {
                // Cache for all directories we checked
                var entry = new IgnoreFileCacheEntry(currentPath);
                foreach (var dir in checkedDirs)
                {
                    _directoryCache.AddOrUpdate(dir, entry);
                }

                return ignoreFile;
            }

            if (current != startDir)
            {
                checkedDirs.Add(currentPath);
            }
        }

        // No .ignore file found - cache null result for all directories
        var nullEntry = new IgnoreFileCacheEntry((string?)null);
        foreach (var dir in checkedDirs)
        {
            _directoryCache.AddOrUpdate(dir, nullEntry);
        }

        return null;
    }

    private ParsedIgnoreCacheEntry? GetParsedRules(FileInfo ignoreFile)
    {
        if (!ignoreFile.Exists)
        {
            _rulesCache.TryRemove(ignoreFile.FullName, out _);
            return null;
        }

        var lastModified = ignoreFile.LastWriteTimeUtc;
        var fileLength = ignoreFile.Length;
        var key = ignoreFile.FullName;

        // Check cache
        if (_rulesCache.TryGet(key, out var cached))
        {
            if (cached.FileLastModified == lastModified && cached.FileLength == fileLength)
            {
                return cached;
            }

            // Stale - need to reparse
            _rulesCache.TryRemove(key, out _);
        }

        // Parse the file
        var parsedEntry = ParseIgnoreFile(ignoreFile, lastModified, fileLength);
        _rulesCache.AddOrUpdate(key, parsedEntry);
        return parsedEntry;
    }

    private static ParsedIgnoreCacheEntry ParseIgnoreFile(FileInfo ignoreFile, DateTime lastModified, long fileLength)
    {
        if (ignoreFile.LinkTarget is null && fileLength == 0)
        {
            return new ParsedIgnoreCacheEntry
            {
                Rules = new Ignore.Ignore(),
                FileLastModified = lastModified,
                FileLength = fileLength,
                IsEmpty = true
            };
        }

        // Resolve symlinks
        var resolvedFile = FileSystemHelper.ResolveLinkTarget(ignoreFile, returnFinalTarget: true) ?? ignoreFile;
        if (!resolvedFile.Exists)
        {
            return new ParsedIgnoreCacheEntry
            {
                Rules = new Ignore.Ignore(),
                FileLastModified = lastModified,
                FileLength = fileLength,
                IsEmpty = true
            };
        }

        var content = File.ReadAllText(resolvedFile.FullName);
        if (string.IsNullOrWhiteSpace(content))
        {
            return new ParsedIgnoreCacheEntry
            {
                Rules = new Ignore.Ignore(),
                FileLastModified = lastModified,
                FileLength = fileLength,
                IsEmpty = true
            };
        }

        var rules = content.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        var ignore = new Ignore.Ignore();
        var validRulesAdded = 0;

        foreach (var rule in rules)
        {
            try
            {
                ignore.Add(rule);
                validRulesAdded++;
            }
            catch (RegexParseException)
            {
                // Ignore invalid patterns
            }
        }

        // No valid rules means treat as empty (ignore all)
        return new ParsedIgnoreCacheEntry
        {
            Rules = ignore,
            FileLastModified = lastModified,
            FileLength = fileLength,
            IsEmpty = validRulesAdded == 0
        };
    }

    private static string GetPathToCheck(string path, bool isDirectory)
    {
        // Normalize Windows paths
        var pathToCheck = IsWindows ? path.NormalizePath('/') : path;

        // Add trailing slash for directories to match "folder/"
        if (isDirectory)
        {
            pathToCheck = string.Concat(pathToCheck.AsSpan().TrimEnd('/'), "/");
        }

        return pathToCheck;
    }

    private readonly record struct IgnoreFileCacheEntry(string? IgnoreFileDirectory);

    private sealed class ParsedIgnoreCacheEntry
    {
        public required Ignore.Ignore Rules { get; init; }

        public required DateTime FileLastModified { get; init; }

        public required long FileLength { get; init; }

        public required bool IsEmpty { get; init; }
    }
}