From 95d7ba8935ac7214805147e694353206a56bddb7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 16 Apr 2022 14:07:09 -0400 Subject: move case-insensitive path lookup into toolkit for reuse --- .../Utilities/CaseInsensitivePathLookup.cs | 137 +++++++++++++++++++++ src/SMAPI/Framework/ContentCoordinator.cs | 4 +- .../Framework/ContentManagers/ModContentManager.cs | 6 +- src/SMAPI/Framework/ContentPack.cs | 6 +- src/SMAPI/Framework/ModHelpers/ModContentHelper.cs | 6 +- src/SMAPI/Framework/ModLoading/ModResolver.cs | 4 +- src/SMAPI/Framework/SCore.cs | 8 +- src/SMAPI/Utilities/CaseInsensitivePathCache.cs | 137 --------------------- 8 files changed, 154 insertions(+), 154 deletions(-) create mode 100644 src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs delete mode 100644 src/SMAPI/Utilities/CaseInsensitivePathCache.cs (limited to 'src') diff --git a/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs b/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs new file mode 100644 index 00000000..2e149e3c --- /dev/null +++ b/src/SMAPI.Toolkit/Utilities/CaseInsensitivePathLookup.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace StardewModdingAPI.Toolkit.Utilities +{ + /// Provides an API for case-insensitive relative path lookups within a root directory. + internal class CaseInsensitivePathLookup + { + /********* + ** Fields + *********/ + /// The root directory path for relative paths. + private readonly string RootPath; + + /// A case-insensitive lookup of file paths within the . 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. + private readonly Lazy> RelativePathCache; + + /// The case-insensitive path caches by root path. + private static readonly Dictionary CachedRoots = new(StringComparer.OrdinalIgnoreCase); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The root directory path for relative paths. + public CaseInsensitivePathLookup(string rootPath) + { + this.RootPath = rootPath; + this.RelativePathCache = new(this.GetRelativePathCache); + } + + /// Get the exact capitalization for a given relative file path. + /// The relative path. + /// Returns the resolved path in file path format, else the normalized . + public string GetFilePath(string relativePath) + { + return this.GetImpl(PathUtilities.NormalizePath(relativePath)); + } + + /// Get the exact capitalization for a given asset name. + /// The relative path. + /// Returns the resolved path in asset name format, else the normalized . + public string GetAssetName(string relativePath) + { + return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath)); + } + + /// Add a relative path that was just created by a SMAPI API. + /// The relative path. This must already be normalized in asset name or file path format. + 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); + } + + /// Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups. + /// The root path to scan. + 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 + *********/ + /// Get the exact capitalization for a given relative path. + /// The relative path. This must already be normalized into asset name or file path format (i.e. using or respectively). + /// Returns the resolved path in the same format if found, else returns the path as-is. + 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; + } + + /// Get a case-insensitive lookup of file paths (see ). + private Dictionary GetRelativePathCache() + { + Dictionary cache = new(StringComparer.OrdinalIgnoreCase); + + foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", SearchOption.AllDirectories)) + { + string relativePath = path.Substring(this.RootPath.Length + 1); + + this.CacheRawPath(cache, relativePath); + } + + return cache; + } + + /// Add a raw relative path to the cache. + /// The cache to update. + /// The relative path to cache, with its exact filesystem capitalization. + private void CacheRawPath(IDictionary cache, string relativePath) + { + string filePath = PathUtilities.NormalizePath(relativePath); + string assetName = PathUtilities.NormalizeAssetName(relativePath); + + cache[filePath] = filePath; + cache[assetName] = assetName; + } + } +} diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index f83d4090..aade7b36 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -15,7 +15,7 @@ using StardewModdingAPI.Framework.Utilities; using StardewModdingAPI.Internal; using StardewModdingAPI.Metadata; using StardewModdingAPI.Toolkit.Serialization; -using StardewModdingAPI.Utilities; +using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using StardewValley.GameData; using xTile; @@ -208,7 +208,7 @@ namespace StardewModdingAPI.Framework jsonHelper: this.JsonHelper, onDisposing: this.OnDisposing, aggressiveMemoryOptimizations: this.AggressiveMemoryOptimizations, - relativePathCache: CaseInsensitivePathCache.GetFor(rootDirectory) + relativePathCache: CaseInsensitivePathLookup.GetCachedFor(rootDirectory) ); this.ContentManagers.Add(manager); return manager; diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index f0f4bce9..8f64c5a8 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -9,7 +9,7 @@ using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; using StardewModdingAPI.Toolkit.Serialization; -using StardewModdingAPI.Utilities; +using StardewModdingAPI.Toolkit.Utilities; using StardewValley; using xTile; using xTile.Format; @@ -33,7 +33,7 @@ namespace StardewModdingAPI.Framework.ContentManagers private readonly IContentManager GameContentManager; /// A case-insensitive lookup of relative paths within the . - private readonly CaseInsensitivePathCache RelativePathCache; + private readonly CaseInsensitivePathLookup RelativePathCache; /// If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder. private readonly string[] LocalTilesheetExtensions = { ".png", ".xnb" }; @@ -56,7 +56,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// A callback to invoke when the content manager is being disposed. /// Whether to enable more aggressive memory optimizations. /// A case-insensitive lookup of relative paths within the . - public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onDisposing, bool aggressiveMemoryOptimizations, CaseInsensitivePathCache relativePathCache) + public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onDisposing, bool aggressiveMemoryOptimizations, CaseInsensitivePathLookup relativePathCache) : base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: true, aggressiveMemoryOptimizations: aggressiveMemoryOptimizations) { this.GameContentManager = gameContentManager; diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 2cfd5cce..dde33c95 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -2,7 +2,7 @@ using System; using System.IO; using StardewModdingAPI.Framework.ModHelpers; using StardewModdingAPI.Toolkit.Serialization; -using StardewModdingAPI.Utilities; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework { @@ -16,7 +16,7 @@ namespace StardewModdingAPI.Framework private readonly JsonHelper JsonHelper; /// A case-insensitive lookup of relative paths within the . - private readonly CaseInsensitivePathCache RelativePathCache; + private readonly CaseInsensitivePathLookup RelativePathCache; /********* @@ -48,7 +48,7 @@ namespace StardewModdingAPI.Framework /// Provides translations stored in the content pack's i18n folder. /// Encapsulates SMAPI's JSON file parsing. /// A case-insensitive lookup of relative paths within the . - public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, CaseInsensitivePathCache relativePathCache) + public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, CaseInsensitivePathLookup relativePathCache) { this.DirectoryPath = directoryPath; this.Manifest = manifest; diff --git a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs index 4a058a48..def0b728 100644 --- a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs @@ -4,7 +4,7 @@ using StardewModdingAPI.Framework.Content; using StardewModdingAPI.Framework.ContentManagers; using StardewModdingAPI.Framework.Exceptions; using StardewModdingAPI.Framework.Reflection; -using StardewModdingAPI.Utilities; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.ModHelpers { @@ -24,7 +24,7 @@ namespace StardewModdingAPI.Framework.ModHelpers private readonly string ModName; /// A case-insensitive lookup of relative paths within the . - private readonly CaseInsensitivePathCache RelativePathCache; + private readonly CaseInsensitivePathLookup RelativePathCache; /// Simplifies access to private code. private readonly Reflector Reflection; @@ -41,7 +41,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The game content manager used for map tilesheets not provided by the mod. /// A case-insensitive lookup of relative paths within the . /// Simplifies access to private code. - public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, CaseInsensitivePathCache relativePathCache, Reflector reflection) + public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, CaseInsensitivePathLookup relativePathCache, Reflector reflection) : base(mod) { string managedAssetPrefix = contentCore.GetManagedAssetPrefix(mod.Manifest.UniqueID); diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index e3c7873c..4a02e90d 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -8,7 +8,7 @@ using StardewModdingAPI.Toolkit.Framework.ModData; using StardewModdingAPI.Toolkit.Framework.ModScanning; using StardewModdingAPI.Toolkit.Framework.UpdateData; using StardewModdingAPI.Toolkit.Serialization.Models; -using StardewModdingAPI.Utilities; +using StardewModdingAPI.Toolkit.Utilities; namespace StardewModdingAPI.Framework.ModLoading { @@ -141,7 +141,7 @@ namespace StardewModdingAPI.Framework.ModLoading } // file doesn't exist - string fileName = CaseInsensitivePathCache.GetFor(mod.DirectoryPath).GetFilePath(mod.Manifest.EntryDll!); + string fileName = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath).GetFilePath(mod.Manifest.EntryDll!); if (!File.Exists(Path.Combine(mod.DirectoryPath, fileName))) { mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist."); diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index d2890c29..b3c9087f 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1748,7 +1748,7 @@ namespace StardewModdingAPI.Framework if (mod.IsContentPack) { IMonitor monitor = this.LogManager.GetMonitor(mod.DisplayName); - CaseInsensitivePathCache relativePathCache = CaseInsensitivePathCache.GetFor(mod.DirectoryPath); + CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath); GameContentHelper gameContentHelper = new(this.ContentCore, mod, mod.DisplayName, monitor, this.Reflection); IModContentHelper modContentHelper = new ModContentHelper(this.ContentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection); TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language); @@ -1767,7 +1767,7 @@ namespace StardewModdingAPI.Framework // get mod info string assemblyPath = Path.Combine( mod.DirectoryPath, - CaseInsensitivePathCache.GetFor(mod.DirectoryPath).GetFilePath(manifest.EntryDll!) + CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath).GetFilePath(manifest.EntryDll!) ); // load mod @@ -1833,7 +1833,7 @@ namespace StardewModdingAPI.Framework { IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name); - CaseInsensitivePathCache relativePathCache = CaseInsensitivePathCache.GetFor(packDirPath); + CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(packDirPath); GameContentHelper gameContentHelper = new(contentCore, mod, packManifest.Name, packMonitor, this.Reflection); IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, mod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection); @@ -1847,7 +1847,7 @@ namespace StardewModdingAPI.Framework IModEvents events = new ModEvents(mod, this.EventManager); ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager); - CaseInsensitivePathCache relativePathCache = CaseInsensitivePathCache.GetFor(mod.DirectoryPath); + CaseInsensitivePathLookup relativePathCache = CaseInsensitivePathLookup.GetCachedFor(mod.DirectoryPath); #pragma warning disable CS0612 // deprecated code ContentHelper contentHelper = new(contentCore, mod.DirectoryPath, mod, monitor, this.Reflection); #pragma warning restore CS0612 diff --git a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs b/src/SMAPI/Utilities/CaseInsensitivePathCache.cs deleted file mode 100644 index 04fdcfae..00000000 --- a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace StardewModdingAPI.Utilities -{ - /// Provides an API for case-insensitive relative path lookups within a root directory. - internal class CaseInsensitivePathCache - { - /********* - ** Fields - *********/ - /// The root directory path for relative paths. - private readonly string RootPath; - - /// A case-insensitive lookup of file paths within the . 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. - private readonly Lazy> RelativePathCache; - - /// The case-insensitive path caches by root path. - private static readonly Dictionary CachesByRootPath = new(StringComparer.OrdinalIgnoreCase); - - - /********* - ** Public methods - *********/ - /// Construct an instance. - /// The root directory path for relative paths. - public CaseInsensitivePathCache(string rootPath) - { - this.RootPath = rootPath; - this.RelativePathCache = new(this.GetRelativePathCache); - } - - /// Get the exact capitalization for a given relative file path. - /// The relative path. - /// Returns the resolved path in file path format, else the normalized . - public string GetFilePath(string relativePath) - { - return this.GetImpl(PathUtilities.NormalizePath(relativePath)); - } - - /// Get the exact capitalization for a given asset name. - /// The relative path. - /// Returns the resolved path in asset name format, else the normalized . - public string GetAssetName(string relativePath) - { - return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath)); - } - - /// Add a relative path that was just created by a SMAPI API. - /// The relative path. This must already be normalized in asset name or file path format. - 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); - } - - /// Get a cached dictionary of relative paths within a root path, for case-insensitive file lookups. - /// The root path to scan. - public static CaseInsensitivePathCache GetFor(string rootPath) - { - rootPath = PathUtilities.NormalizePath(rootPath); - - if (!CaseInsensitivePathCache.CachesByRootPath.TryGetValue(rootPath, out CaseInsensitivePathCache? cache)) - CaseInsensitivePathCache.CachesByRootPath[rootPath] = cache = new CaseInsensitivePathCache(rootPath); - - return cache; - } - - - /********* - ** Private methods - *********/ - /// Get the exact capitalization for a given relative path. - /// The relative path. This must already be normalized into asset name or file path format (i.e. using or respectively). - /// Returns the resolved path in the same format if found, else returns the path as-is. - 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; - } - - /// Get a case-insensitive lookup of file paths (see ). - private Dictionary GetRelativePathCache() - { - Dictionary cache = new(StringComparer.OrdinalIgnoreCase); - - foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", SearchOption.AllDirectories)) - { - string relativePath = path.Substring(this.RootPath.Length + 1); - - this.CacheRawPath(cache, relativePath); - } - - return cache; - } - - /// Add a raw relative path to the cache. - /// The cache to update. - /// The relative path to cache, with its exact filesystem capitalization. - private void CacheRawPath(IDictionary cache, string relativePath) - { - string filePath = PathUtilities.NormalizePath(relativePath); - string assetName = PathUtilities.NormalizeAssetName(relativePath); - - cache[filePath] = filePath; - cache[assetName] = assetName; - } - } -} -- cgit