PathExtensions.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.IO;
  4. using MediaBrowser.Common.Providers;
  5. namespace Emby.Server.Implementations.Library
  6. {
  7. /// <summary>
  8. /// Class providing extension methods for working with paths.
  9. /// </summary>
  10. public static class PathExtensions
  11. {
  12. /// <summary>
  13. /// Gets the attribute value.
  14. /// </summary>
  15. /// <param name="str">The STR.</param>
  16. /// <param name="attribute">The attrib.</param>
  17. /// <returns>System.String.</returns>
  18. /// <exception cref="ArgumentException"><paramref name="str" /> or <paramref name="attribute" /> is empty.</exception>
  19. public static string? GetAttributeValue(this ReadOnlySpan<char> str, ReadOnlySpan<char> attribute)
  20. {
  21. if (str.Length == 0)
  22. {
  23. throw new ArgumentException("String can't be empty.", nameof(str));
  24. }
  25. if (attribute.Length == 0)
  26. {
  27. throw new ArgumentException("String can't be empty.", nameof(attribute));
  28. }
  29. var attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
  30. // Must be at least 3 characters after the attribute =, ], any character.
  31. var maxIndex = str.Length - attribute.Length - 3;
  32. while (attributeIndex > -1 && attributeIndex < maxIndex)
  33. {
  34. var attributeEnd = attributeIndex + attribute.Length;
  35. if (attributeIndex > 0
  36. && str[attributeIndex - 1] == '['
  37. && (str[attributeEnd] == '=' || str[attributeEnd] == '-'))
  38. {
  39. var closingIndex = str[attributeEnd..].IndexOf(']');
  40. // Must be at least 1 character before the closing bracket.
  41. if (closingIndex > 1)
  42. {
  43. return str[(attributeEnd + 1)..(attributeEnd + closingIndex)].Trim().ToString();
  44. }
  45. }
  46. str = str[attributeEnd..];
  47. attributeIndex = str.IndexOf(attribute, StringComparison.OrdinalIgnoreCase);
  48. }
  49. // for imdbid we also accept pattern matching
  50. if (attribute.Equals("imdbid", StringComparison.OrdinalIgnoreCase))
  51. {
  52. var match = ProviderIdParsers.TryFindImdbId(str, out var imdbId);
  53. return match ? imdbId.ToString() : null;
  54. }
  55. return null;
  56. }
  57. /// <summary>
  58. /// Replaces a sub path with another sub path and normalizes the final path.
  59. /// </summary>
  60. /// <param name="path">The original path.</param>
  61. /// <param name="subPath">The original sub path.</param>
  62. /// <param name="newSubPath">The new sub path.</param>
  63. /// <param name="newPath">The result of the sub path replacement.</param>
  64. /// <returns>The path after replacing the sub path.</returns>
  65. /// <exception cref="ArgumentNullException"><paramref name="path" />, <paramref name="newSubPath" /> or <paramref name="newSubPath" /> is empty.</exception>
  66. public static bool TryReplaceSubPath(
  67. [NotNullWhen(true)] this string? path,
  68. [NotNullWhen(true)] string? subPath,
  69. [NotNullWhen(true)] string? newSubPath,
  70. [NotNullWhen(true)] out string? newPath)
  71. {
  72. newPath = null;
  73. if (string.IsNullOrEmpty(path)
  74. || string.IsNullOrEmpty(subPath)
  75. || string.IsNullOrEmpty(newSubPath)
  76. || subPath.Length > path.Length)
  77. {
  78. return false;
  79. }
  80. subPath = subPath.NormalizePath(out var newDirectorySeparatorChar);
  81. path = path.NormalizePath(newDirectorySeparatorChar);
  82. // We have to ensure that the sub path ends with a directory separator otherwise we'll get weird results
  83. // when the sub path matches a similar but in-complete subpath
  84. var oldSubPathEndsWithSeparator = subPath[^1] == newDirectorySeparatorChar;
  85. if (!path.StartsWith(subPath, StringComparison.OrdinalIgnoreCase))
  86. {
  87. return false;
  88. }
  89. if (path.Length > subPath.Length
  90. && !oldSubPathEndsWithSeparator
  91. && path[subPath.Length] != newDirectorySeparatorChar)
  92. {
  93. return false;
  94. }
  95. var newSubPathTrimmed = newSubPath.AsSpan().TrimEnd(newDirectorySeparatorChar);
  96. // Ensure that the path with the old subpath removed starts with a leading dir separator
  97. int idx = oldSubPathEndsWithSeparator ? subPath.Length - 1 : subPath.Length;
  98. newPath = string.Concat(newSubPathTrimmed, path.AsSpan(idx));
  99. return true;
  100. }
  101. /// <summary>
  102. /// Retrieves the full resolved path and normalizes path separators to the <see cref="Path.DirectorySeparatorChar"/>.
  103. /// </summary>
  104. /// <param name="path">The path to canonicalize.</param>
  105. /// <returns>The fully expanded, normalized path.</returns>
  106. public static string Canonicalize(this string path)
  107. {
  108. return Path.GetFullPath(path).NormalizePath();
  109. }
  110. /// <summary>
  111. /// Normalizes the path's directory separator character to the currently defined <see cref="Path.DirectorySeparatorChar"/>.
  112. /// </summary>
  113. /// <param name="path">The path to normalize.</param>
  114. /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
  115. [return: NotNullIfNotNull(nameof(path))]
  116. public static string? NormalizePath(this string? path)
  117. {
  118. return path.NormalizePath(Path.DirectorySeparatorChar);
  119. }
  120. /// <summary>
  121. /// Normalizes the path's directory separator character.
  122. /// </summary>
  123. /// <param name="path">The path to normalize.</param>
  124. /// <param name="separator">The separator character the path now uses or <see langword="null"/>.</param>
  125. /// <returns>The normalized path string or <see langword="null"/> if the input path is null or empty.</returns>
  126. [return: NotNullIfNotNull(nameof(path))]
  127. public static string? NormalizePath(this string? path, out char separator)
  128. {
  129. if (string.IsNullOrEmpty(path))
  130. {
  131. separator = default;
  132. return path;
  133. }
  134. var newSeparator = '\\';
  135. // True normalization is still not possible https://github.com/dotnet/runtime/issues/2162
  136. // The reasoning behind this is that a forward slash likely means it's a Linux path and
  137. // so the whole path should be normalized to use / and vice versa for Windows (although Windows doesn't care much).
  138. if (path.Contains('/', StringComparison.Ordinal))
  139. {
  140. newSeparator = '/';
  141. }
  142. separator = newSeparator;
  143. return path.NormalizePath(newSeparator);
  144. }
  145. /// <summary>
  146. /// Normalizes the path's directory separator character to the specified character.
  147. /// </summary>
  148. /// <param name="path">The path to normalize.</param>
  149. /// <param name="newSeparator">The replacement directory separator character. Must be a valid directory separator.</param>
  150. /// <returns>The normalized path.</returns>
  151. /// <exception cref="ArgumentException">Thrown if the new separator character is not a directory separator.</exception>
  152. [return: NotNullIfNotNull(nameof(path))]
  153. public static string? NormalizePath(this string? path, char newSeparator)
  154. {
  155. const char Bs = '\\';
  156. const char Fs = '/';
  157. if (!(newSeparator == Bs || newSeparator == Fs))
  158. {
  159. throw new ArgumentException("The character must be a directory separator.");
  160. }
  161. if (string.IsNullOrEmpty(path))
  162. {
  163. return path;
  164. }
  165. return newSeparator == Bs ? path.Replace(Fs, newSeparator) : path.Replace(Bs, newSeparator);
  166. }
  167. }
  168. }