< 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: 51
Uncovered lines: 3
Coverable lines: 54
Total lines: 194
Line coverage: 94.4%
Branch coverage
96%
Covered branches: 50
Total branches: 52
Branch coverage: 96.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
GetAttributeValue(...)100%2222100%
TryReplaceSubPath(...)94.44%18.051894.73%
Canonicalize(...)100%11100%
NormalizePath(...)100%11100%
NormalizePath(...)75%4.25475%
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        {
 3122            if (str.Length == 0)
 23            {
 224                throw new ArgumentException("String can't be empty.", nameof(str));
 25            }
 26
 2927            if (attribute.Length == 0)
 28            {
 129                throw new ArgumentException("String can't be empty.", nameof(attribute));
 30            }
 31
 2832            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.
 2836            var maxIndex = str.Length - attribute.Length - 2;
 3637            while (attributeIndex > -1 && attributeIndex < maxIndex)
 38            {
 2639                var attributeEnd = attributeIndex + attribute.Length;
 2640                if (attributeIndex > 0
 2641                    && str[attributeIndex - 1] == '['
 2642                    && (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
 43                {
 2144                    var closingIndex = str[attributeEnd..].IndexOf(']');
 45                    // Must be at least 1 character before the closing bracket.
 2146                    if (closingIndex > 1)
 47                    {
 1848                        return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
 49                    }
 50                }
 51
 852                str = str[attributeEnd..];
 853                attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
 54            }
 55
 56            // for imdbid we also accept pattern matching
 1057            if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
 58            {
 259                var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
 260                return match ? imdbId.ToString() : null;
 61            }
 62
 863            return null;
 64        }
 65
 66        /// <summary>
 67        /// Replaces a sub path with another sub path and normalizes the final path.
 68        /// </summary>
 69        /// <param name="path">The original path.</param>
 70        /// <param name="subPath">The original sub path.</param>
 71        /// <param name="newSubPath">The new sub path.</param>
 72        /// <param name="newPath">The result of the sub path replacement.</param>
 73        /// <returns>The path after replacing the sub path.</returns>
 74        /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramre
 75        public static bool TryReplaceSubPath(
 76            [NotNullWhen(true)] this string? path,
 77            [NotNullWhen(true)] string? subPath,
 78            [NotNullWhen(true)] string? newSubPath,
 79            [NotNullWhen(true)] out string? newPath)
 80        {
 1781            newPath = null;
 82
 1783            if (string.IsNullOrEmpty(path)
 1784                || string.IsNullOrEmpty(subPath)
 1785                || string.IsNullOrEmpty(newSubPath)
 1786                || subPath.Length > path.Length)
 87            {
 888                return false;
 89            }
 90
 991            subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
 992            path = path.NormalizePath(newDirectorySeparatorChar);
 93
 94            // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
 95            // when the sub path matches a similar but in-complete subpath
 996            var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
 997            if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
 98            {
 199                return false;
 100            }
 101
 8102            if (path.Length > subPath.Length
 8103                && !oldSubPathEndsWithSeparator
 8104                && path[subPath.Length] != newDirectorySeparatorChar)
 105            {
 0106                return false;
 107            }
 108
 8109            var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
 110            // Ensure that the path with the old subpath removed starts with a leading dir separator
 8111            int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
 8112            newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
 113
 8114            return true;
 115        }
 116
 117        /// <summary>
 118        /// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorCha
 119        /// </summary>
 120        /// <param name="path">The path to canonicalize.</param>
 121        /// <returns>The fully expanded, normalized path.</returns>
 122        public static string Canonicalize(this string path)
 123        {
 15124            return Path.GetFullPath(path).NormalizePath();
 125        }
 126
 127        /// <summary>
 128        /// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySepara
 129        /// </summary>
 130        /// <param name="path">The path to normalize.</param>
 131        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 132        [return: NotNullIfNotNull(nameof(path))]
 133        public static string? NormalizePath(this string? path)
 134        {
 30135            return path.NormalizePath(Path.DirectorySeparatorChar);
 136        }
 137
 138        /// <summary>
 139        /// Normalizes the path's directory separator character.
 140        /// </summary>
 141        /// <param name="path">The path to normalize.</param>
 142        /// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
 143        /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
 144        [return: NotNullIfNotNull(nameof(path))]
 145        public static string? NormalizePath(this string? path, out char separator)
 146        {
 12147            if (string.IsNullOrEmpty(path))
 148            {
 0149                separator = default;
 0150                return path;
 151            }
 152
 12153            var newSeparator = '\\';
 154
 155            // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
 156            // The reasoning behind this is that a forward slash likely means it's a Linux path and
 157            // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care
 12158            if (path.Contains('/', StringComparison.Ordinal))
 159            {
 11160                newSeparator = '/';
 161            }
 162
 12163            separator = newSeparator;
 164
 12165            return path.NormalizePath(newSeparator);
 166        }
 167
 168        /// <summary>
 169        /// Normalizes the path's directory separator character to the specified character.
 170        /// </summary>
 171        /// <param name="path">The path to normalize.</param>
 172        /// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separato
 173        /// <returns>The normalized path.</returns>
 174        /// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exc
 175        [return: NotNullIfNotNull(nameof(path))]
 176        public static string? NormalizePath(this string? path, char newSeparator)
 177        {
 178            const char Bs = '\\';
 179            const char Fs = '/';
 180
 59181            if (!(newSeparator == Bs || newSeparator == Fs))
 182            {
 1183                throw new ArgumentException("The character must be a directory separator.");
 184            }
 185
 58186            if (string.IsNullOrEmpty(path))
 187            {
 3188                return path;
 189            }
 190
 55191            return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
 192        }
 193    }
 194}