diff options
Diffstat (limited to 'src/SMAPI.Toolkit/Utilities')
-rw-r--r-- | src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs | 139 | ||||
-rw-r--r-- | src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs | 2 | ||||
-rw-r--r-- | src/SMAPI.Toolkit/Utilities/PathUtilities.cs | 33 |
3 files changed, 164 insertions, 10 deletions
diff --git a/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs b/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs new file mode 100644 index 00000000..12fad008 --- /dev/null +++ b/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace StardewModdingAPI.Toolkit.Utilities +{ + /// <summary>Provides an API for case-insensitive relative path lookups within a root directory.</summary> + internal class CaseInsensitivePathLookup + { + /********* + ** Fields + *********/ + /// <summary>The root directory path for relative paths.</summary> + private readonly string RootPath; + + /// <summary>A case-insensitive lookup of file paths within the <see cref="RootPath"/>. Each path is listed in both file path and asset name format, so it's usable in both contexts without needing to re-parse paths.</summary> + private readonly Lazy<Dictionary<string, string>> RelativePathCache; + + /// <summary>The case-insensitive path caches by root path.</summary> + private static readonly Dictionary<string, CaseInsensitivePathLookup> CachedRoots = new(StringComparer.OrdinalIgnoreCase); + + + /********* + ** Public methods + *********/ + /// <summary>Construct an instance.</summary> + /// <param name="rootPath">The root directory path for relative paths.</param> + /// <param name="searchOption">Which directories to scan from the root.</param> + public CaseInsensitivePathLookup(string rootPath, SearchOption searchOption = SearchOption.AllDirectories) + { + this.RootPath = rootPath; + this.RelativePathCache = new(() => this.GetRelativePathCache(searchOption)); + } + + /// <summary>Get the exact capitalization for a given relative file path.</summary> + /// <param name="relativePath">The relative path.</param> + /// <remarks>Returns the resolved path in file path format, else the normalized <paramref name="relativePath"/>.</remarks> + public string GetFilePath(string relativePath) + { + return this.GetImpl(PathUtilities.NormalizePath(relativePath)); + } + + /// <summary>Get the exact capitalization for a given asset name.</summary> + /// <param name="relativePath">The relative path.</param> + /// <remarks>Returns the resolved path in asset name format, else the normalized <paramref name="relativePath"/>.</remarks> + public string GetAssetName(string relativePath) + { + return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath)); + } + + /// <summary>Add a relative path that was just created by a SMAPI API.</summary> + /// <param name="relativePath">The relative path. This must already be normalized in asset name or file path format.</param> + public void Add(string relativePath) + { + // skip if cache isn't created yet (no need to add files manually in that case) + if (!this.RelativePathCache.IsValueCreated) + return; + + // skip if already cached + if (this.RelativePathCache.Value.ContainsKey(relativePath)) + return; + + // make sure path exists + relativePath = PathUtilities.NormalizePath(relativePath); + if (!File.Exists(Path.Combine(this.RootPath, relativePath))) + throw new InvalidOperationException($"Can't add relative path '{relativePath}' to the case-insensitive cache for '{this.RootPath}' because that file doesn't exist."); + + // cache path + this.CacheRawPath(this.RelativePathCache.Value, relativePath); + } + + /// <summary>Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups.</summary> + /// <param name="rootPath">The root path to scan.</param> + public static CaseInsensitivePathLookup GetCachedFor(string rootPath) + { + rootPath = PathUtilities.NormalizePath(rootPath); + + if (!CaseInsensitivePathLookup.CachedRoots.TryGetValue(rootPath, out CaseInsensitivePathLookup? cache)) + CaseInsensitivePathLookup.CachedRoots[rootPath] = cache = new CaseInsensitivePathLookup(rootPath); + + return cache; + } + + + /********* + ** Private methods + *********/ + /// <summary>Get the exact capitalization for a given relative path.</summary> + /// <param name="relativePath">The relative path. This must already be normalized into asset name or file path format (i.e. using <see cref="PathUtilities.NormalizeAssetName"/> or <see cref="PathUtilities.NormalizePath"/> respectively).</param> + /// <remarks>Returns the resolved path in the same format if found, else returns the path as-is.</remarks> + private string GetImpl(string relativePath) + { + // invalid path + if (string.IsNullOrWhiteSpace(relativePath)) + return relativePath; + + // already cached + if (this.RelativePathCache.Value.TryGetValue(relativePath, out string? resolved)) + return resolved; + + // keep capitalization as-is + if (File.Exists(Path.Combine(this.RootPath, relativePath))) + { + // file exists but isn't cached for some reason + // cache it now so any later references to it are case-insensitive + this.CacheRawPath(this.RelativePathCache.Value, relativePath); + } + return relativePath; + } + + /// <summary>Get a case-insensitive lookup of file paths (see <see cref="RelativePathCache"/>).</summary> + /// <param name="searchOption">Which directories to scan from the root.</param> + private Dictionary<string, string> GetRelativePathCache(SearchOption searchOption) + { + Dictionary<string, string> cache = new(StringComparer.OrdinalIgnoreCase); + + foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", searchOption)) + { + string relativePath = path.Substring(this.RootPath.Length + 1); + + this.CacheRawPath(cache, relativePath); + } + + return cache; + } + + /// <summary>Add a raw relative path to the cache.</summary> + /// <param name="cache">The cache to update.</param> + /// <param name="relativePath">The relative path to cache, with its exact filesystem capitalization.</param> + private void CacheRawPath(IDictionary<string, string> cache, string relativePath) + { + string filePath = PathUtilities.NormalizePath(relativePath); + string assetName = PathUtilities.NormalizeAssetName(relativePath); + + cache[filePath] = filePath; + cache[assetName] = assetName; + } + } +} diff --git a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs index 7536337a..1791c5b3 100644 --- a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs +++ b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics.CodeAnalysis; using StardewModdingAPI.Toolkit.Framework; namespace StardewModdingAPI.Toolkit.Utilities @@ -34,7 +33,6 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <summary>Get the human-readable OS name and version.</summary> /// <param name="platform">The current platform.</param> - [SuppressMessage("ReSharper", "EmptyGeneralCatchClause", Justification = "Error suppressed deliberately to fallback to default behaviour.")] public static string GetFriendlyPlatformName(Platform platform) { return LowLevelEnvironmentUtility.GetFriendlyPlatformName(platform.ToString()); diff --git a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs index 2e9e5eac..136279f2 100644 --- a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs +++ b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.IO; using System.Linq; @@ -36,8 +37,11 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <param name="path">The path to split.</param> /// <param name="limit">The number of segments to match. Any additional segments will be merged into the last returned part.</param> [Pure] - public static string[] GetSegments(string path, int? limit = null) + public static string[] GetSegments(string? path, int? limit = null) { + if (path == null) + return Array.Empty<string>(); + return limit.HasValue ? path.Split(PathUtilities.PossiblePathSeparators, limit.Value, StringSplitOptions.RemoveEmptyEntries) : path.Split(PathUtilities.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries); @@ -45,8 +49,16 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <summary>Normalize an asset name to match how MonoGame's content APIs would normalize and cache it.</summary> /// <param name="assetName">The asset name to normalize.</param> - public static string NormalizeAssetName(string assetName) + [Pure] +#if NET5_0_OR_GREATER + [return: NotNullIfNotNull("assetName")] +#endif + public static string? NormalizeAssetName(string? assetName) { + assetName = assetName?.Trim(); + if (string.IsNullOrEmpty(assetName)) + return assetName; + return string.Join(PathUtilities.PreferredAssetSeparator.ToString(), PathUtilities.GetSegments(assetName)); // based on MonoGame's ContentManager.Load<T> logic } @@ -54,7 +66,10 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <param name="path">The file path to normalize.</param> /// <remarks>This should only be used for file paths. For asset names, use <see cref="NormalizeAssetName"/> instead.</remarks> [Pure] - public static string NormalizePath(string path) +#if NET5_0_OR_GREATER + [return: NotNullIfNotNull("path")] +#endif + public static string? NormalizePath(string? path) { path = path?.Trim(); if (string.IsNullOrEmpty(path)) @@ -100,8 +115,8 @@ namespace StardewModdingAPI.Toolkit.Utilities // though, this is only for compatibility with the mod build package. // convert to URIs - Uri from = new Uri(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); - Uri to = new Uri(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); + Uri from = new(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); + Uri to = new(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); if (from.Scheme != to.Scheme) throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{sourceDir}'."); @@ -132,7 +147,7 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <summary>Get whether a path is relative and doesn't try to climb out of its containing folder (e.g. doesn't contain <c>../</c>).</summary> /// <param name="path">The path to check.</param> [Pure] - public static bool IsSafeRelativePath(string path) + public static bool IsSafeRelativePath(string? path) { if (string.IsNullOrWhiteSpace(path)) return true; @@ -145,9 +160,11 @@ namespace StardewModdingAPI.Toolkit.Utilities /// <summary>Get whether a string is a valid 'slug', containing only basic characters that are safe in all contexts (e.g. filenames, URLs, etc).</summary> /// <param name="str">The string to check.</param> [Pure] - public static bool IsSlug(string str) + public static bool IsSlug(string? str) { - return !Regex.IsMatch(str, "[^a-z0-9_.-]", RegexOptions.IgnoreCase); + return + string.IsNullOrWhiteSpace(str) + || !Regex.IsMatch(str, "[^a-z0-9_.-]", RegexOptions.IgnoreCase); } } } |