< 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
93%
Covered lines: 57
Uncovered lines: 4
Coverable lines: 61
Total lines: 204
Line coverage: 93.4%
Branch coverage
94%
Covered branches: 55
Total branches: 58
Branch coverage: 94.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 10/25/2025 - 12:09:58 AM Line coverage: 94.4% (51/54) Branch coverage: 96.1% (50/52) Total lines: 1942/3/2026 - 12:13:02 AM Line coverage: 93.4% (57/61) Branch coverage: 94.8% (55/58) Total lines: 204 10/25/2025 - 12:09:58 AM Line coverage: 94.4% (51/54) Branch coverage: 96.1% (50/52) Total lines: 1942/3/2026 - 12:13:02 AM Line coverage: 93.4% (57/61) Branch coverage: 94.8% (55/58) Total lines: 204

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
GetAttributeValue(...)96.42%282896.29%
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        {
 4222            if (str.Length == 0)
 23            {
 224                throw new ArgumentException("String can't be empty.", nameof(str));
 25            }
 26
 4027            if (attribute.Length == 0)
 28            {
 129                throw new ArgumentException("String can't be empty.", nameof(attribute));
 30            }
 31
 3932            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.
 3936            var maxIndex = str.Length - attribute.Length - 2;
 5237            while (attributeIndex > -1 && attributeIndex < maxIndex)
 38            {
 3939                var attributeEnd = attributeIndex + attribute.Length;
 3940                if (attributeIndex > 0)
 41                {
 3642                    var attributeOpener = str[attributeIndex - 1];
 3643                    var attributeCloser = attributeOpener switch
 3644                    {
 2145                        '[' => ']',
 746                        '(' => ')',
 847                        '{' => '}',
 048                         _ => '\0'
 3649                    };
 3650                    if (attributeCloser != '\0' && (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
 51                    {
 3352                        var closingIndex = str[attributeEnd..].IndexOf(attributeCloser);
 53
 54                        // Must be at least 1 character before the closing bracket.
 3355                        if (closingIndex > 1)
 56                        {
 2657                            return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
 58                        }
 59                    }
 60                }
 61
 1362                str = str[attributeEnd..];
 1363                attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
 64            }
 65
 66            // for imdbid we also accept pattern matching
 1367            if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
 68            {
 269                var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
 270                return match ? imdbId.ToString() : null;
 71            }
 72
 1173            return null;
 74        }
 75
 76        /// <summary>
 77        /// Replaces a sub path with another sub path and normalizes the final path.
 78        /// </summary>
 79        /// <param name="path">The original path.</param>
 80        /// <param name="subPath">The original sub path.</param>
 81        /// <param name="newSubPath">The new sub path.</param>
 82        /// <param name="newPath">The result of the sub path replacement.</param>
 83        /// <returns>The path after replacing the sub path.</returns>
 84        /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramre
 85        public static bool TryReplaceSubPath(
 86            [NotNullWhen(true)] this string? path,
 87            [NotNullWhen(true)] string? subPath,
 88            [NotNullWhen(true)] string? newSubPath,
 89            [NotNullWhen(true)] out string? newPath)
 90        {
 1791            newPath = null;
 92
 1793            if (string.IsNullOrEmpty(path)
 1794                || string.IsNullOrEmpty(subPath)
 1795                || string.IsNullOrEmpty(newSubPath)
 1796                || subPath.Length > path.Length)
 97            {
 898                return false;
 99            }
 100
 9101            subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
 9102            path = path.NormalizePath(newDirectorySeparatorChar);
 103
 104            // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
 105            // when the sub path matches a similar but in-complete subpath
 9106            var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
 9107            if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
 108            {
 1109                return false;
 110            }
 111
 8112            if (path.Length > subPath.Length
 8113                && !oldSubPathEndsWithSeparator
 8114                && path[subPath.Length] != newDirectorySeparatorChar)
 115            {
 0116                return false;
 117            }
 118
 8119            var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
 120            // Ensure that the path with the old subpath removed starts with a leading dir separator
 8121            int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
 8122            newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
 123
 8124            return true;
 125        }
 126
 127        /// <summary>
 128        /// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorCha
 129        /// </summary>
 130        /// <param name="path">The path to canonicalize.</param>
 131        /// <returns>The fully expanded, normalized path.</returns>
 132        public static string Canonicalize(this string path)
 133        {
 15134            return Path.GetFullPath(path).NormalizePath();
 135        }
 136
 137        /// <summary>
 138        /// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySepara
 139        /// </summary>
 140        /// <param name="path">The path to normalize.</param>
 141        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 142        [return: NotNullIfNotNull(nameof(path))]
 143        public static string? NormalizePath(this string? path)
 144        {
 30145            return path.NormalizePath(Path.DirectorySeparatorChar);
 146        }
 147
 148        /// <summary>
 149        /// Normalizes the path's directory separator character.
 150        /// </summary>
 151        /// <param name="path">The path to normalize.</param>
 152        /// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
 153        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 154        [return: NotNullIfNotNull(nameof(path))]
 155        public static string? NormalizePath(this string? path, out char separator)
 156        {
 12157            if (string.IsNullOrEmpty(path))
 158            {
 0159                separator = default;
 0160                return path;
 161            }
 162
 12163            var newSeparator = '\\';
 164
 165            // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
 166            // The reasoning behind this is that a forward slash likely means it's a Linux path and
 167            // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care
 12168            if (path.Contains('/', StringComparison.Ordinal))
 169            {
 11170                newSeparator = '/';
 171            }
 172
 12173            separator = newSeparator;
 174
 12175            return path.NormalizePath(newSeparator);
 176        }
 177
 178        /// <summary>
 179        /// Normalizes the path's directory separator character to the specified character.
 180        /// </summary>
 181        /// <param name="path">The path to normalize.</param>
 182        /// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separato
 183        /// <returns>The normalized path.</returns>
 184        /// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exc
 185        [return: NotNullIfNotNull(nameof(path))]
 186        public static string? NormalizePath(this string? path, char newSeparator)
 187        {
 188            const char Bs = '\\';
 189            const char Fs = '/';
 190
 67191            if (!(newSeparator == Bs || newSeparator == Fs))
 192            {
 1193                throw new ArgumentException("The character must be a directory separator.");
 194            }
 195
 66196            if (string.IsNullOrEmpty(path))
 197            {
 3198                return path;
 199            }
 200
 63201            return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
 202        }
 203    }
 204}