< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Library.PathExtensions
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Library/PathExtensions.cs
Line coverage
92%
Covered lines: 60
Uncovered lines: 5
Coverable lines: 65
Total lines: 214
Line coverage: 92.3%
Branch coverage
93%
Covered branches: 58
Total branches: 62
Branch coverage: 93.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 2/13/2026 - 12:11:21 AM Line coverage: 93.4% (57/61) Branch coverage: 94.8% (55/58) Total lines: 2045/8/2026 - 12:15:13 AM Line coverage: 92.3% (60/65) Branch coverage: 93.5% (58/62) Total lines: 214 2/13/2026 - 12:11:21 AM Line coverage: 93.4% (57/61) Branch coverage: 94.8% (55/58) Total lines: 2045/8/2026 - 12:15:13 AM Line coverage: 92.3% (60/65) Branch coverage: 93.5% (58/62) Total lines: 214

Coverage delta

Coverage delta 2 -2

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
GetAttributeValue(...)93.75%323293.54%
TryReplaceSubPath(...)94.44%181894.73%
Canonicalize(...)100%11100%
NormalizePath(...)100%11100%
NormalizePath(...)75%4475%
NormalizePath(...)100%88100%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/Library/PathExtensions.cs

#LineLine coverage
 1using System;
 2using System.Diagnostics.CodeAnalysis;
 3using System.IO;
 4using MediaBrowser.Common.Providers;
 5
 6namespace Emby.Server.Implementations.Library
 7{
 8    /// <summary>
 9    /// Class providing extension methods for working with paths.
 10    /// </summary>
 11    public static class PathExtensions
 12    {
 13        /// <summary>
 14        /// Gets the attribute value.
 15        /// </summary>
 16        /// <param name="str">The STR.</param>
 17        /// <param name="attribute">The attrib.</param>
 18        /// <returns>System.String.</returns>
 19        /// <exception cref="ArgumentException"><paramref name="str" /> or <paramref name="attribute" /> is empty.</exce
 20        public static string? GetAttributeValue(this ReadOnlySpan<char> str, ReadOnlySpan<char> attribute)
 21        {
 26122            if (str.Length == 0)
 23            {
 224                throw new ArgumentException("String can't be empty.", nameof(str));
 25            }
 26
 25927            if (attribute.Length == 0)
 28            {
 129                throw new ArgumentException("String can't be empty.", nameof(attribute));
 30            }
 31
 25832            var attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
 33
 34            // Must be at least 3 characters after the attribute =, ], any character,
 35            // then we offset it by 1, because we want the index and not length.
 25836            var maxIndex = str.Length - attribute.Length - 2;
 27237            while (attributeIndex > -1 && attributeIndex < maxIndex)
 38            {
 7639                var attributeEnd = attributeIndex + attribute.Length;
 7640                if (attributeIndex > 0)
 41                {
 7242                    var attributeOpener = str[attributeIndex - 1];
 7243                    var attributeCloser = attributeOpener switch
 7244                    {
 5445                        '[' => ']',
 1046                        '(' => ')',
 847                        '{' => '}',
 048                        _ => '\0'
 7249                    };
 7250                    if (attributeCloser != '\0' && (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
 51                    {
 6952                        var closingIndex = str[attributeEnd..].IndexOf(attributeCloser);
 53
 54                        // Must be at least 1 character before the closing bracket.
 6955                        if (closingIndex > 1)
 56                        {
 6257                            return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
 58                        }
 59                    }
 60                }
 61
 1462                str = str[attributeEnd..];
 1463                attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
 64            }
 65
 66            // for imdbid we also accept pattern matching
 19667            if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
 68            {
 2569                var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
 2570                return match ? imdbId.ToString() : null;
 71            }
 72
 73            // Allow tmdb as an alias for tmdbid
 17174            if (attribute.Equals("tmdbid", StringComparison.OrdinalIgnoreCase))
 75            {
 4076                var tmdbValue = str.GetAttributeValue("tmdb");
 4077                if (tmdbValue is not null)
 78                {
 079                    return tmdbValue;
 80                }
 81            }
 82
 17183            return null;
 84        }
 85
 86        /// <summary>
 87        /// Replaces a sub path with another sub path and normalizes the final path.
 88        /// </summary>
 89        /// <param name="path">The original path.</param>
 90        /// <param name="subPath">The original sub path.</param>
 91        /// <param name="newSubPath">The new sub path.</param>
 92        /// <param name="newPath">The result of the sub path replacement.</param>
 93        /// <returns>The path after replacing the sub path.</returns>
 94        /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramre
 95        public static bool TryReplaceSubPath(
 96            [NotNullWhen(true)] this string? path,
 97            [NotNullWhen(true)] string? subPath,
 98            [NotNullWhen(true)] string? newSubPath,
 99            [NotNullWhen(true)] out string? newPath)
 100        {
 17101            newPath = null;
 102
 17103            if (string.IsNullOrEmpty(path)
 17104                || string.IsNullOrEmpty(subPath)
 17105                || string.IsNullOrEmpty(newSubPath)
 17106                || subPath.Length > path.Length)
 107            {
 8108                return false;
 109            }
 110
 9111            subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
 9112            path = path.NormalizePath(newDirectorySeparatorChar);
 113
 114            // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
 115            // when the sub path matches a similar but in-complete subpath
 9116            var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
 9117            if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
 118            {
 1119                return false;
 120            }
 121
 8122            if (path.Length > subPath.Length
 8123                && !oldSubPathEndsWithSeparator
 8124                && path[subPath.Length] != newDirectorySeparatorChar)
 125            {
 0126                return false;
 127            }
 128
 8129            var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
 130            // Ensure that the path with the old subpath removed starts with a leading dir separator
 8131            int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
 8132            newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
 133
 8134            return true;
 135        }
 136
 137        /// <summary>
 138        /// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorCha
 139        /// </summary>
 140        /// <param name="path">The path to canonicalize.</param>
 141        /// <returns>The fully expanded, normalized path.</returns>
 142        public static string Canonicalize(this string path)
 143        {
 15144            return Path.GetFullPath(path).NormalizePath();
 145        }
 146
 147        /// <summary>
 148        /// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySepara
 149        /// </summary>
 150        /// <param name="path">The path to normalize.</param>
 151        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 152        [return: NotNullIfNotNull(nameof(path))]
 153        public static string? NormalizePath(this string? path)
 154        {
 30155            return path.NormalizePath(Path.DirectorySeparatorChar);
 156        }
 157
 158        /// <summary>
 159        /// Normalizes the path's directory separator character.
 160        /// </summary>
 161        /// <param name="path">The path to normalize.</param>
 162        /// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
 163        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 164        [return: NotNullIfNotNull(nameof(path))]
 165        public static string? NormalizePath(this string? path, out char separator)
 166        {
 12167            if (string.IsNullOrEmpty(path))
 168            {
 0169                separator = default;
 0170                return path;
 171            }
 172
 12173            var newSeparator = '\\';
 174
 175            // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
 176            // The reasoning behind this is that a forward slash likely means it's a Linux path and
 177            // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care
 12178            if (path.Contains('/', StringComparison.Ordinal))
 179            {
 11180                newSeparator = '/';
 181            }
 182
 12183            separator = newSeparator;
 184
 12185            return path.NormalizePath(newSeparator);
 186        }
 187
 188        /// <summary>
 189        /// Normalizes the path's directory separator character to the specified character.
 190        /// </summary>
 191        /// <param name="path">The path to normalize.</param>
 192        /// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separato
 193        /// <returns>The normalized path.</returns>
 194        /// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exc
 195        [return: NotNullIfNotNull(nameof(path))]
 196        public static string? NormalizePath(this string? path, char newSeparator)
 197        {
 198            const char Bs = '\\';
 199            const char Fs = '/';
 200
 67201            if (!(newSeparator == Bs || newSeparator == Fs))
 202            {
 1203                throw new ArgumentException("The character must be a directory separator.");
 204            }
 205
 66206            if (string.IsNullOrEmpty(path))
 207            {
 3208                return path;
 209            }
 210
 63211            return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
 212        }
 213    }
 214}