< 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
94%
Covered lines: 72
Uncovered lines: 4
Coverable lines: 76
Total lines: 245
Line coverage: 94.7%
Branch coverage
91%
Covered branches: 79
Total branches: 86
Branch coverage: 91.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/1/2026 - 12:13:05 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: 2147/21/2026 - 12:16:33 AM Line coverage: 94.7% (72/76) Branch coverage: 91.8% (79/86) Total lines: 245 5/1/2026 - 12:13:05 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: 2147/21/2026 - 12:16:33 AM Line coverage: 94.7% (72/76) Branch coverage: 91.8% (79/86) Total lines: 245

Coverage delta

Coverage delta 3 -3

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
GetAttributeValue(...)91.07%565697.61%
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        {
 28422            if (str.Length == 0)
 23            {
 224                throw new ArgumentException("String can't be empty.", nameof(str));
 25            }
 26
 28227            if (attribute.Length == 0)
 28            {
 129                throw new ArgumentException("String can't be empty.", nameof(attribute));
 30            }
 31
 32            // Allow tmdb as an alias for tmdbid, tvdb for tvdbid, etc.
 33            // The code below only supports aliases for attributes in the form of "<alias>id".
 34            ReadOnlySpan<char> shortAttr = attribute switch
 35            {
 37736                _ when attribute.Equals("tmdbid", StringComparison.OrdinalIgnoreCase) => "tmdb",
 23537                _ when attribute.Equals("tvdbid", StringComparison.OrdinalIgnoreCase) => "tvdb",
 18738                _ when attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase) => "imdb",
 8339                _ => ReadOnlySpan<char>.Empty
 40            };
 41
 104842            for (int strIndex = 0, attributeIndex = 0; attributeIndex > -1;)
 43            {
 44                // We may want to use imdbid pattern matching later, so we don't want to modify the original 'str'.
 31645                var subStr = str[strIndex..];
 31646                int attributeEnd = 0;
 47
 31648                if (shortAttr.Length > 0)
 49                {
 50                    // If we are using an alias it should be shorter (and a prefix), so let's search for that.
 23351                    attributeIndex = subStr.IndexOf(shortAttr, StringComparison.OrdinalIgnoreCase);
 23352                    attributeEnd = attributeIndex + shortAttr.Length;
 53                }
 54                else
 55                {
 8356                    attributeIndex = subStr.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
 8357                    attributeEnd = attributeIndex + attribute.Length;
 58                }
 59
 60                // The next iteration should start at the end of the attribute we just found.
 61                // If attributeIndex < 0, the loop will end and strIndex won't be used again.
 31662                strIndex += attributeEnd;
 63
 31664                if (attributeIndex > 0)
 65                {
 13666                    var attributeOpener = subStr[attributeIndex - 1];
 13667                    var attributeCloser = attributeOpener switch
 13668                    {
 8769                        '[' => ']',
 2570                        '(' => ')',
 2471                        '{' => '}',
 072                        _ => '\0'
 13673                    };
 74
 13675                    if (attributeCloser != '\0')
 76                    {
 13677                        if (shortAttr.Length > 0
 13678                            && attributeEnd + 1 < subStr.Length
 13679                            && (subStr[attributeEnd] is 'i' or 'I')
 13680                            && (subStr[attributeEnd + 1] is 'd' or 'D'))
 81                        {
 82                            // We were searching for a shortened attribute, but it's followed by "id" - let's skip it.
 7883                            attributeEnd += 2;
 84                        }
 85
 86                        // attributeEnd points at '='.
 87                        // We need at least 1 more character and the closing bracket after that.
 13688                        if (attributeEnd + 2 < subStr.Length && (subStr[attributeEnd] is '=' or '-'))
 89                        {
 12990                            var closingIndex = subStr[attributeEnd..].IndexOf(attributeCloser);
 91
 92                            // Must be at least 1 character before the closing bracket.
 12993                            if (closingIndex > 1)
 94                            {
 11595                                var trimmed = subStr[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim();
 96
 11597                                if (trimmed.Length > 0)
 98                                {
 11199                                    return trimmed.ToString();
 100                                }
 101                            }
 102                        }
 103                    }
 104                }
 105            }
 106
 107            // for imdbid we also accept pattern matching
 170108            if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
 109            {
 26110                var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
 26111                return match ? imdbId.ToString() : null;
 112            }
 113
 144114            return null;
 115        }
 116
 117        /// <summary>
 118        /// Replaces a sub path with another sub path and normalizes the final path.
 119        /// </summary>
 120        /// <param name="path">The original path.</param>
 121        /// <param name="subPath">The original sub path.</param>
 122        /// <param name="newSubPath">The new sub path.</param>
 123        /// <param name="newPath">The result of the sub path replacement.</param>
 124        /// <returns>The path after replacing the sub path.</returns>
 125        /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramre
 126        public static bool TryReplaceSubPath(
 127            [NotNullWhen(true)] this string? path,
 128            [NotNullWhen(true)] string? subPath,
 129            [NotNullWhen(true)] string? newSubPath,
 130            [NotNullWhen(true)] out string? newPath)
 131        {
 17132            newPath = null;
 133
 17134            if (string.IsNullOrEmpty(path)
 17135                || string.IsNullOrEmpty(subPath)
 17136                || string.IsNullOrEmpty(newSubPath)
 17137                || subPath.Length > path.Length)
 138            {
 8139                return false;
 140            }
 141
 9142            subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
 9143            path = path.NormalizePath(newDirectorySeparatorChar);
 144
 145            // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
 146            // when the sub path matches a similar but in-complete subpath
 9147            var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
 9148            if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
 149            {
 1150                return false;
 151            }
 152
 8153            if (path.Length > subPath.Length
 8154                && !oldSubPathEndsWithSeparator
 8155                && path[subPath.Length] != newDirectorySeparatorChar)
 156            {
 0157                return false;
 158            }
 159
 8160            var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
 161            // Ensure that the path with the old subpath removed starts with a leading dir separator
 8162            int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
 8163            newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
 164
 8165            return true;
 166        }
 167
 168        /// <summary>
 169        /// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorCha
 170        /// </summary>
 171        /// <param name="path">The path to canonicalize.</param>
 172        /// <returns>The fully expanded, normalized path.</returns>
 173        public static string Canonicalize(this string path)
 174        {
 15175            return Path.GetFullPath(path).NormalizePath();
 176        }
 177
 178        /// <summary>
 179        /// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySepara
 180        /// </summary>
 181        /// <param name="path">The path to normalize.</param>
 182        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 183        [return: NotNullIfNotNull(nameof(path))]
 184        public static string? NormalizePath(this string? path)
 185        {
 30186            return path.NormalizePath(Path.DirectorySeparatorChar);
 187        }
 188
 189        /// <summary>
 190        /// Normalizes the path's directory separator character.
 191        /// </summary>
 192        /// <param name="path">The path to normalize.</param>
 193        /// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
 194        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 195        [return: NotNullIfNotNull(nameof(path))]
 196        public static string? NormalizePath(this string? path, out char separator)
 197        {
 12198            if (string.IsNullOrEmpty(path))
 199            {
 0200                separator = default;
 0201                return path;
 202            }
 203
 12204            var newSeparator = '\\';
 205
 206            // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
 207            // The reasoning behind this is that a forward slash likely means it's a Linux path and
 208            // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care
 12209            if (path.Contains('/', StringComparison.Ordinal))
 210            {
 11211                newSeparator = '/';
 212            }
 213
 12214            separator = newSeparator;
 215
 12216            return path.NormalizePath(newSeparator);
 217        }
 218
 219        /// <summary>
 220        /// Normalizes the path's directory separator character to the specified character.
 221        /// </summary>
 222        /// <param name="path">The path to normalize.</param>
 223        /// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separato
 224        /// <returns>The normalized path.</returns>
 225        /// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exc
 226        [return: NotNullIfNotNull(nameof(path))]
 227        public static string? NormalizePath(this string? path, char newSeparator)
 228        {
 229            const char Bs = '\\';
 230            const char Fs = '/';
 231
 67232            if (!(newSeparator == Bs || newSeparator == Fs))
 233            {
 1234                throw new ArgumentException("The character must be a directory separator.");
 235            }
 236
 66237            if (string.IsNullOrEmpty(path))
 238            {
 3239                return path;
 240            }
 241
 63242            return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
 243        }
 244    }
 245}