PathExtensions.cs 8.2 KB

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