simplify and rewrite case-insensitive file path feature

This commit is contained in:
Jesse Plamondon-Willard 2022-05-07 23:12:33 -04:00
parent d4ff9f3f5c
commit 3db0353126
No known key found for this signature in database
GPG Key ID: CF8B1456B3E29F49
13 changed files with 158 additions and 182 deletions

View File

@ -2,6 +2,8 @@
# Release notes
## Upcoming release
* For players:
* Improved performance of case-insensitive file paths.
* For mod authors:
* Dynamic content packs created via `helper.ContentPacks.CreateTemporary` or `CreateFake` are now listed in the log file.
* Fixed assets loaded through a fake content pack not working correctly since 3.14.0.

View File

@ -133,7 +133,7 @@ namespace SMAPI.Tests.Core
[Test(Description = "Assert that validation doesn't fail if there are no mods installed.")]
public void ValidateManifests_NoMods_DoesNothing()
{
new ModResolver().ValidateManifests(Array.Empty<ModMetadata>(), apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false);
new ModResolver().ValidateManifests(Array.Empty<ModMetadata>(), apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false);
}
[Test(Description = "Assert that validation skips manifests that have already failed without calling any other properties.")]
@ -144,7 +144,7 @@ namespace SMAPI.Tests.Core
mock.Setup(p => p.Status).Returns(ModMetadataStatus.Failed);
// act
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false);
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false);
// assert
mock.VerifyGet(p => p.Status, Times.Once, "The validation did not check the manifest status.");
@ -161,7 +161,7 @@ namespace SMAPI.Tests.Core
});
// act
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false);
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false);
// assert
mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata.");
@ -175,7 +175,7 @@ namespace SMAPI.Tests.Core
mock.Setup(p => p.Manifest).Returns(this.GetManifest(minimumApiVersion: "1.1"));
// act
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false);
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false);
// assert
mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata.");
@ -190,7 +190,7 @@ namespace SMAPI.Tests.Core
Directory.CreateDirectory(directoryPath);
// act
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance);
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup);
// assert
mock.Verify(p => p.SetStatus(ModMetadataStatus.Failed, It.IsAny<ModFailReason>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once, "The validation did not fail the metadata.");
@ -207,7 +207,7 @@ namespace SMAPI.Tests.Core
Mock<IModMetadata> modB = this.GetMetadata(this.GetManifest(id: "Mod A", name: "Mod B", version: "1.0"), allowStatusChange: true);
// act
new ModResolver().ValidateManifests(new[] { modA.Object, modB.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance, validateFilesExist: false);
new ModResolver().ValidateManifests(new[] { modA.Object, modB.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup, validateFilesExist: false);
// assert
modA.Verify(p => p.SetStatus(ModMetadataStatus.Failed, ModFailReason.Duplicate, It.IsAny<string>(), It.IsAny<string>()), Times.AtLeastOnce, "The validation did not fail the first mod with a unique ID.");
@ -233,7 +233,7 @@ namespace SMAPI.Tests.Core
mock.Setup(p => p.DirectoryPath).Returns(modFolder);
// act
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFilePathLookup: _ => MinimalPathLookup.Instance);
new ModResolver().ValidateManifests(new[] { mock.Object }, apiVersion: new SemanticVersion("1.0"), getUpdateUrl: _ => null, getFileLookup: this.GetFileLookup);
// assert
// if Moq doesn't throw a method-not-setup exception, the validation didn't override the status.
@ -483,6 +483,13 @@ namespace SMAPI.Tests.Core
return Path.Combine(Path.GetTempPath(), "smapi-unit-tests", Guid.NewGuid().ToString("N"));
}
/// <summary>Get a file lookup for a given directory.</summary>
/// <param name="rootDirectory">The full path to the directory.</param>
private IFileLookup GetFileLookup(string rootDirectory)
{
return MinimalFileLookup.GetCachedFor(rootDirectory);
}
/// <summary>Get a randomized basic manifest.</summary>
/// <param name="id">The <see cref="IManifest.UniqueID"/> value, or <c>null</c> for a generated value.</param>
/// <param name="name">The <see cref="IManifest.Name"/> value, or <c>null</c> for a generated value.</param>

View File

@ -114,10 +114,11 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning
/// <summary>Extract information from a mod folder.</summary>
/// <param name="root">The root folder containing mods.</param>
/// <param name="searchFolder">The folder to search for a mod.</param>
public ModFolder ReadFolder(DirectoryInfo root, DirectoryInfo searchFolder)
/// <param name="useCaseInsensitiveFilePaths">Whether to match file paths case-insensitively, even on Linux.</param>
public ModFolder ReadFolder(DirectoryInfo root, DirectoryInfo searchFolder, bool useCaseInsensitiveFilePaths)
{
// find manifest.json
FileInfo? manifestFile = this.FindManifest(searchFolder);
FileInfo? manifestFile = this.FindManifest(searchFolder, useCaseInsensitiveFilePaths);
// set appropriate invalid-mod error
if (manifestFile == null)
@ -225,7 +226,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning
// treat as mod folder
else
yield return this.ReadFolder(root, folder);
yield return this.ReadFolder(root, folder, useCaseInsensitiveFilePaths);
}
/// <summary>Consolidate adjacent folders into one mod folder, if possible.</summary>
@ -250,7 +251,8 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning
/// <summary>Find the manifest for a mod folder.</summary>
/// <param name="folder">The folder to search.</param>
private FileInfo? FindManifest(DirectoryInfo folder)
/// <param name="useCaseInsensitiveFilePaths">Whether to match file paths case-insensitively, even on Linux.</param>
private FileInfo? FindManifest(DirectoryInfo folder, bool useCaseInsensitiveFilePaths)
{
// check for conventional manifest in current folder
const string defaultName = "manifest.json";
@ -259,14 +261,14 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning
return file;
// check for manifest with incorrect capitalization
if (useCaseInsensitiveFilePaths)
{
CaseInsensitivePathLookup pathLookup = new(folder.FullName, SearchOption.TopDirectoryOnly); // don't use GetCachedFor, since we only need it temporarily
string realName = pathLookup.GetFilePath(defaultName);
if (realName != defaultName)
file = new(Path.Combine(folder.FullName, realName));
CaseInsensitiveFileLookup fileLookup = new(folder.FullName, SearchOption.TopDirectoryOnly); // don't use GetCachedFor, since we only need it temporarily
file = fileLookup.GetFile(defaultName);
return file.Exists
? file
: null;
}
if (file.Exists)
return file;
// not found
return null;

View File

@ -4,8 +4,8 @@ using System.IO;
namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
{
/// <summary>An API for case-insensitive relative path lookups within a root directory.</summary>
internal class CaseInsensitivePathLookup : IFilePathLookup
/// <summary>An API for case-insensitive file lookups within a root directory.</summary>
internal class CaseInsensitiveFileLookup : IFileLookup
{
/*********
** Fields
@ -16,8 +16,8 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
/// <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);
/// <summary>The case-insensitive file lookups by root path.</summary>
private static readonly Dictionary<string, CaseInsensitiveFileLookup> CachedRoots = new(StringComparer.OrdinalIgnoreCase);
/*********
@ -26,22 +26,28 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
/// <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)
public CaseInsensitiveFileLookup(string rootPath, SearchOption searchOption = SearchOption.AllDirectories)
{
this.RootPath = rootPath;
this.RootPath = PathUtilities.NormalizePath(rootPath);
this.RelativePathCache = new(() => this.GetRelativePathCache(searchOption));
}
/// <inheritdoc />
public string GetFilePath(string relativePath)
public FileInfo GetFile(string relativePath)
{
return this.GetImpl(PathUtilities.NormalizePath(relativePath));
}
// invalid path
if (string.IsNullOrWhiteSpace(relativePath))
throw new InvalidOperationException("Can't get a file from an empty relative path.");
/// <inheritdoc />
public string GetAssetName(string relativePath)
{
return this.GetImpl(PathUtilities.NormalizeAssetName(relativePath));
// already cached
if (this.RelativePathCache.Value.TryGetValue(relativePath, out string? resolved))
return new(Path.Combine(this.RootPath, resolved));
// keep capitalization as-is
FileInfo file = new(Path.Combine(this.RootPath, relativePath));
if (file.Exists)
this.RelativePathCache.Value[relativePath] = relativePath;
return file;
}
/// <inheritdoc />
@ -61,17 +67,17 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
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);
this.RelativePathCache.Value[relativePath] = 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)
public static CaseInsensitiveFileLookup GetCachedFor(string rootPath)
{
rootPath = PathUtilities.NormalizePath(rootPath);
if (!CaseInsensitivePathLookup.CachedRoots.TryGetValue(rootPath, out CaseInsensitivePathLookup? cache))
CaseInsensitivePathLookup.CachedRoots[rootPath] = cache = new CaseInsensitivePathLookup(rootPath);
if (!CaseInsensitiveFileLookup.CachedRoots.TryGetValue(rootPath, out CaseInsensitiveFileLookup? cache))
CaseInsensitiveFileLookup.CachedRoots[rootPath] = cache = new CaseInsensitiveFileLookup(rootPath);
return cache;
}
@ -80,29 +86,6 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
/*********
** 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)
@ -112,23 +95,10 @@ namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
foreach (string path in Directory.EnumerateFiles(this.RootPath, "*", searchOption))
{
string relativePath = path.Substring(this.RootPath.Length + 1);
this.CacheRawPath(cache, relativePath);
cache[relativePath] = 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;
}
}
}

View File

@ -1,20 +1,16 @@
using System.IO;
namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
{
/// <summary>An API for relative path lookups within a root directory.</summary>
internal interface IFilePathLookup
/// <summary>An API for file lookups within a root directory.</summary>
internal interface IFileLookup
{
/// <summary>Get the actual path for a given relative file path.</summary>
/// <summary>Get the file for a given relative file path, if it exists.</summary>
/// <param name="relativePath">The relative path.</param>
/// <remarks>Returns the resolved path in file path format, else the normalized <paramref name="relativePath"/>.</remarks>
string GetFilePath(string relativePath);
/// <summary>Get the actual path 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>
string GetAssetName(string relativePath);
FileInfo GetFile(string 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>
/// <param name="relativePath">The relative path.</param>
void Add(string relativePath);
}
}

View File

@ -1,31 +1,52 @@
using System.Collections.Generic;
using System.IO;
namespace StardewModdingAPI.Toolkit.Utilities.PathLookups
{
/// <summary>An API for relative path lookups within a root directory with minimal preprocessing.</summary>
internal class MinimalPathLookup : IFilePathLookup
/// <summary>An API for file lookups within a root directory with minimal preprocessing.</summary>
internal class MinimalFileLookup : IFileLookup
{
/*********
** Accessors
*********/
/// <summary>A singleton instance for reuse.</summary>
public static readonly MinimalPathLookup Instance = new();
/// <summary>The file lookups by root path.</summary>
private static readonly Dictionary<string, MinimalFileLookup> CachedRoots = new();
/// <summary>The root directory path for relative paths.</summary>
private readonly string RootPath;
/*********
** Public methods
*********/
/// <inheritdoc />
public string GetFilePath(string relativePath)
/// <summary>Construct an instance.</summary>
/// <param name="rootPath">The root directory path for relative paths.</param>
public MinimalFileLookup(string rootPath)
{
return PathUtilities.NormalizePath(relativePath);
this.RootPath = rootPath;
}
/// <inheritdoc />
public string GetAssetName(string relativePath)
public FileInfo GetFile(string relativePath)
{
return PathUtilities.NormalizeAssetName(relativePath);
return new(
Path.Combine(this.RootPath, PathUtilities.NormalizePath(relativePath))
);
}
/// <inheritdoc />
public void Add(string 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 MinimalFileLookup GetCachedFor(string rootPath)
{
rootPath = PathUtilities.NormalizePath(rootPath);
if (!MinimalFileLookup.CachedRoots.TryGetValue(rootPath, out MinimalFileLookup? lookup))
MinimalFileLookup.CachedRoots[rootPath] = lookup = new MinimalFileLookup(rootPath);
return lookup;
}
}
}

View File

@ -32,8 +32,8 @@ namespace StardewModdingAPI.Framework
/// <summary>An asset key prefix for assets from SMAPI mod folders.</summary>
private readonly string ManagedPrefix = "SMAPI";
/// <summary>Get a file path lookup for the given directory.</summary>
private readonly Func<string, IFilePathLookup> GetFilePathLookup;
/// <summary>Get a file lookup for the given directory.</summary>
private readonly Func<string, IFileLookup> GetFileLookup;
/// <summary>Encapsulates monitoring and logging.</summary>
private readonly IMonitor Monitor;
@ -123,12 +123,12 @@ namespace StardewModdingAPI.Framework
/// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param>
/// <param name="onLoadingFirstAsset">A callback to invoke the first time *any* game content manager loads an asset.</param>
/// <param name="onAssetLoaded">A callback to invoke when an asset is fully loaded.</param>
/// <param name="getFilePathLookup">Get a file path lookup for the given directory.</param>
/// <param name="getFileLookup">Get a file lookup for the given directory.</param>
/// <param name="onAssetsInvalidated">A callback to invoke when any asset names have been invalidated from the cache.</param>
/// <param name="requestAssetOperations">Get the load/edit operations to apply to an asset by querying registered <see cref="IContentEvents.AssetRequested"/> event handlers.</param>
public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, Func<string, IFilePathLookup> getFilePathLookup, Action<IList<IAssetName>> onAssetsInvalidated, Func<IAssetInfo, IList<AssetOperationGroup>> requestAssetOperations)
public ContentCoordinator(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action onLoadingFirstAsset, Action<BaseContentManager, IAssetName> onAssetLoaded, Func<string, IFileLookup> getFileLookup, Action<IList<IAssetName>> onAssetsInvalidated, Func<IAssetInfo, IList<AssetOperationGroup>> requestAssetOperations)
{
this.GetFilePathLookup = getFilePathLookup;
this.GetFileLookup = getFileLookup;
this.Monitor = monitor ?? throw new ArgumentNullException(nameof(monitor));
this.Reflection = reflection;
this.JsonHelper = jsonHelper;
@ -200,7 +200,7 @@ namespace StardewModdingAPI.Framework
reflection: this.Reflection,
jsonHelper: this.JsonHelper,
onDisposing: this.OnDisposing,
relativePathLookup: this.GetFilePathLookup(rootDirectory)
fileLookup: this.GetFileLookup(rootDirectory)
);
this.ContentManagers.Add(manager);
return manager;

View File

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
@ -33,11 +34,11 @@ namespace StardewModdingAPI.Framework.ContentManagers
/// <summary>The game content manager used for map tilesheets not provided by the mod.</summary>
private readonly IContentManager GameContentManager;
/// <summary>A lookup for relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary>
private readonly IFilePathLookup RelativePathLookup;
/// <summary>A lookup for files within the <see cref="ContentManager.RootDirectory"/>.</summary>
private readonly IFileLookup FileLookup;
/// <summary>If a map tilesheet's image source has no file extensions, the file extensions to check for in the local mod folder.</summary>
private readonly string[] LocalTilesheetExtensions = { ".png", ".xnb" };
private static readonly HashSet<string> LocalTilesheetExtensions = new(StringComparer.OrdinalIgnoreCase) { ".png", ".xnb" };
/*********
@ -55,12 +56,12 @@ namespace StardewModdingAPI.Framework.ContentManagers
/// <param name="reflection">Simplifies access to private code.</param>
/// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param>
/// <param name="onDisposing">A callback to invoke when the content manager is being disposed.</param>
/// <param name="relativePathLookup">A lookup for relative paths within the <paramref name="rootDirectory"/>.</param>
public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, IFilePathLookup relativePathLookup)
/// <param name="fileLookup">A lookup for files within the <paramref name="rootDirectory"/>.</param>
public ModContentManager(string name, IContentManager gameContentManager, IServiceProvider serviceProvider, string modName, string rootDirectory, CultureInfo currentCulture, ContentCoordinator coordinator, IMonitor monitor, Reflector reflection, JsonHelper jsonHelper, Action<BaseContentManager> onDisposing, IFileLookup fileLookup)
: base(name, serviceProvider, rootDirectory, currentCulture, coordinator, monitor, reflection, onDisposing, isNamespaced: true)
{
this.GameContentManager = gameContentManager;
this.RelativePathLookup = relativePathLookup;
this.FileLookup = fileLookup;
this.JsonHelper = jsonHelper;
this.ModName = modName;
@ -73,7 +74,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
if (base.DoesAssetExist<T>(assetName))
return true;
FileInfo file = this.GetModFile(assetName.Name);
FileInfo file = this.GetModFile<T>(assetName.Name);
return file.Exists;
}
@ -103,7 +104,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
try
{
// get file
FileInfo file = this.GetModFile(assetName.Name);
FileInfo file = this.GetModFile<T>(assetName.Name);
if (!file.Exists)
throw this.GetLoadError(assetName, "the specified path doesn't exist.");
@ -139,9 +140,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
/// <exception cref="ArgumentException">The <paramref name="key"/> is empty or contains invalid characters.</exception>
public IAssetName GetInternalAssetKey(string key)
{
FileInfo file = this.GetModFile(key);
string relativePath = Path.GetRelativePath(this.RootDirectory, file.FullName);
string internalKey = Path.Combine(this.Name, relativePath);
string internalKey = Path.Combine(this.Name, PathUtilities.NormalizeAssetName(key));
return this.Coordinator.ParseAssetName(internalKey, allowLocales: false);
}
@ -253,19 +252,17 @@ namespace StardewModdingAPI.Framework.ContentManagers
}
/// <summary>Get a file from the mod folder.</summary>
/// <typeparam name="T">The expected asset type.</typeparam>
/// <param name="path">The asset path relative to the content folder.</param>
private FileInfo GetModFile(string path)
private FileInfo GetModFile<T>(string path)
{
// map to case-insensitive path if needed
path = this.RelativePathLookup.GetFilePath(path);
// get exact file
FileInfo file = this.FileLookup.GetFile(path);
// try exact match
FileInfo file = new(Path.Combine(this.FullRootDirectory, path));
// try with default extension
if (!file.Exists)
// try with default image extensions
if (!file.Exists && typeof(Texture2D).IsAssignableFrom(typeof(T)) && !ModContentManager.LocalTilesheetExtensions.Contains(file.Extension))
{
foreach (string extension in this.LocalTilesheetExtensions)
foreach (string extension in ModContentManager.LocalTilesheetExtensions)
{
FileInfo result = new(file.FullName + extension);
if (result.Exists)
@ -385,7 +382,7 @@ namespace StardewModdingAPI.Framework.ContentManagers
// get relative to map file
{
string localKey = Path.Combine(modRelativeMapFolder, relativePath);
if (this.GetModFile(localKey).Exists)
if (this.GetModFile<Texture2D>(localKey).Exists)
{
assetName = this.GetInternalAssetKey(localKey);
return true;

View File

@ -16,8 +16,8 @@ namespace StardewModdingAPI.Framework
/// <summary>Encapsulates SMAPI's JSON file parsing.</summary>
private readonly JsonHelper JsonHelper;
/// <summary>A lookup for relative paths within the <see cref="DirectoryPath"/>.</summary>
private readonly IFilePathLookup RelativePathCache;
/// <summary>A lookup for files within the <see cref="DirectoryPath"/>.</summary>
private readonly IFileLookup FileLookup;
/*********
@ -48,15 +48,15 @@ namespace StardewModdingAPI.Framework
/// <param name="content">Provides an API for loading content assets from the content pack's folder.</param>
/// <param name="translation">Provides translations stored in the content pack's <c>i18n</c> folder.</param>
/// <param name="jsonHelper">Encapsulates SMAPI's JSON file parsing.</param>
/// <param name="relativePathCache">A lookup for relative paths within the <paramref name="directoryPath"/>.</param>
public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, IFilePathLookup relativePathCache)
/// <param name="fileLookup">A lookup for files within the <paramref name="directoryPath"/>.</param>
public ContentPack(string directoryPath, IManifest manifest, IModContentHelper content, TranslationHelper translation, JsonHelper jsonHelper, IFileLookup fileLookup)
{
this.DirectoryPath = directoryPath;
this.Manifest = manifest;
this.ModContent = content;
this.TranslationImpl = translation;
this.JsonHelper = jsonHelper;
this.RelativePathCache = relativePathCache;
this.FileLookup = fileLookup;
}
/// <inheritdoc />
@ -83,10 +83,17 @@ namespace StardewModdingAPI.Framework
{
path = PathUtilities.NormalizePath(path);
FileInfo file = this.GetFile(path, out path);
FileInfo file = this.GetFile(path);
bool didExist = file.Exists;
this.JsonHelper.WriteJsonFile(file.FullName, data);
this.RelativePathCache.Add(path);
if (!didExist)
{
this.FileLookup.Add(
Path.GetRelativePath(this.DirectoryPath, file.FullName)
);
}
}
/// <inheritdoc />
@ -111,21 +118,11 @@ namespace StardewModdingAPI.Framework
/// <summary>Get the underlying file info.</summary>
/// <param name="relativePath">The normalized file path relative to the content pack directory.</param>
private FileInfo GetFile(string relativePath)
{
return this.GetFile(relativePath, out _);
}
/// <summary>Get the underlying file info.</summary>
/// <param name="relativePath">The normalized file path relative to the content pack directory.</param>
/// <param name="actualRelativePath">The relative path after case-insensitive matching.</param>
private FileInfo GetFile(string relativePath, out string actualRelativePath)
{
if (!PathUtilities.IsSafeRelativePath(relativePath))
throw new InvalidOperationException($"You must call {nameof(IContentPack)} methods with a relative path.");
actualRelativePath = this.RelativePathCache.GetFilePath(relativePath);
return new FileInfo(Path.Combine(this.DirectoryPath, actualRelativePath));
return this.FileLookup.GetFile(relativePath);
}
}
}

View File

@ -1,10 +1,8 @@
using System;
using Microsoft.Xna.Framework.Content;
using StardewModdingAPI.Framework.Content;
using StardewModdingAPI.Framework.ContentManagers;
using StardewModdingAPI.Framework.Exceptions;
using StardewModdingAPI.Framework.Reflection;
using StardewModdingAPI.Toolkit.Utilities.PathLookups;
namespace StardewModdingAPI.Framework.ModHelpers
{
@ -23,9 +21,6 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <summary>The friendly mod name for use in errors.</summary>
private readonly string ModName;
/// <summary>A lookup for relative paths within the <see cref="ContentManager.RootDirectory"/>.</summary>
private readonly IFilePathLookup RelativePathLookup;
/// <summary>Simplifies access to private code.</summary>
private readonly Reflector Reflection;
@ -39,9 +34,8 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <param name="mod">The mod using this instance.</param>
/// <param name="modName">The friendly mod name for use in errors.</param>
/// <param name="gameContentManager">The game content manager used for map tilesheets not provided by the mod.</param>
/// <param name="relativePathLookup">A lookup for relative paths within the <paramref name="relativePathLookup"/>.</param>
/// <param name="reflection">Simplifies access to private code.</param>
public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, IFilePathLookup relativePathLookup, Reflector reflection)
public ModContentHelper(ContentCoordinator contentCore, string modFolderPath, IModMetadata mod, string modName, IContentManager gameContentManager, Reflector reflection)
: base(mod)
{
string managedAssetPrefix = contentCore.GetManagedAssetPrefix(mod.Manifest.UniqueID);
@ -49,7 +43,6 @@ namespace StardewModdingAPI.Framework.ModHelpers
this.ContentCore = contentCore;
this.ModContentManager = contentCore.CreateModContentManager(managedAssetPrefix, modName, modFolderPath, gameContentManager);
this.ModName = modName;
this.RelativePathLookup = relativePathLookup;
this.Reflection = reflection;
}
@ -57,8 +50,6 @@ namespace StardewModdingAPI.Framework.ModHelpers
public T Load<T>(string relativePath)
where T : notnull
{
relativePath = this.RelativePathLookup.GetAssetName(relativePath);
IAssetName assetName = this.ContentCore.ParseAssetName(relativePath, allowLocales: false);
try
@ -74,7 +65,6 @@ namespace StardewModdingAPI.Framework.ModHelpers
/// <inheritdoc />
public IAssetName GetInternalAssetName(string relativePath)
{
relativePath = this.RelativePathLookup.GetAssetName(relativePath);
return this.ModContentManager.GetInternalAssetKey(relativePath);
}
@ -85,9 +75,7 @@ namespace StardewModdingAPI.Framework.ModHelpers
if (data == null)
throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value.");
relativePath = relativePath != null
? this.RelativePathLookup.GetAssetName(relativePath)
: $"temp/{Guid.NewGuid():N}";
relativePath ??= $"temp/{Guid.NewGuid():N}";
return new AssetDataForObject(
locale: this.ContentCore.GetLocale(),

View File

@ -85,11 +85,11 @@ namespace StardewModdingAPI.Framework.ModLoading
/// <summary>Preprocess and load an assembly.</summary>
/// <param name="mod">The mod for which the assembly is being loaded.</param>
/// <param name="assemblyPath">The assembly file path.</param>
/// <param name="assemblyFile">The assembly file.</param>
/// <param name="assumeCompatible">Assume the mod is compatible, even if incompatible code is detected.</param>
/// <returns>Returns the rewrite metadata for the preprocessed assembly.</returns>
/// <exception cref="IncompatibleInstructionException">An incompatible CIL instruction was found while rewriting the assembly.</exception>
public Assembly Load(IModMetadata mod, string assemblyPath, bool assumeCompatible)
public Assembly Load(IModMetadata mod, FileInfo assemblyFile, bool assumeCompatible)
{
// get referenced local assemblies
AssemblyParseResult[] assemblies;
@ -100,19 +100,19 @@ namespace StardewModdingAPI.Framework.ModLoading
where name != null
select name
);
assemblies = this.GetReferencedLocalAssemblies(new FileInfo(assemblyPath), visitedAssemblyNames, this.AssemblyDefinitionResolver).ToArray();
assemblies = this.GetReferencedLocalAssemblies(assemblyFile, visitedAssemblyNames, this.AssemblyDefinitionResolver).ToArray();
}
// validate load
if (!assemblies.Any() || assemblies[0].Status == AssemblyLoadStatus.Failed)
{
throw new SAssemblyLoadFailedException(!File.Exists(assemblyPath)
? $"Could not load '{assemblyPath}' because it doesn't exist."
: $"Could not load '{assemblyPath}'."
throw new SAssemblyLoadFailedException(!assemblyFile.Exists
? $"Could not load '{assemblyFile.FullName}' because it doesn't exist."
: $"Could not load '{assemblyFile.FullName}'."
);
}
if (assemblies.Last().Status == AssemblyLoadStatus.AlreadyLoaded) // mod assembly is last in dependency order
throw new SAssemblyLoadFailedException($"Could not load '{assemblyPath}' because it was already loaded. Do you have two copies of this mod?");
throw new SAssemblyLoadFailedException($"Could not load '{assemblyFile.FullName}' because it was already loaded. Do you have two copies of this mod?");
// rewrite & load assemblies in leaf-to-root order
bool oneAssembly = assemblies.Length == 1;

View File

@ -58,11 +58,11 @@ namespace StardewModdingAPI.Framework.ModLoading
/// <param name="mods">The mod manifests to validate.</param>
/// <param name="apiVersion">The current SMAPI version.</param>
/// <param name="getUpdateUrl">Get an update URL for an update key (if valid).</param>
/// <param name="getFilePathLookup">Get a file path lookup for the given directory.</param>
/// <param name="getFileLookup">Get a file lookup for the given directory.</param>
/// <param name="validateFilesExist">Whether to validate that files referenced in the manifest (like <see cref="IManifest.EntryDll"/>) exist on disk. This can be disabled to only validate the manifest itself.</param>
[SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "Manifest values may be null before they're validated.")]
[SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse", Justification = "Manifest values may be null before they're validated.")]
public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion apiVersion, Func<string, string?> getUpdateUrl, Func<string, IFilePathLookup> getFilePathLookup, bool validateFilesExist = true)
public void ValidateManifests(IEnumerable<IModMetadata> mods, ISemanticVersion apiVersion, Func<string, string?> getUpdateUrl, Func<string, IFileLookup> getFileLookup, bool validateFilesExist = true)
{
mods = mods.ToArray();
@ -147,9 +147,9 @@ namespace StardewModdingAPI.Framework.ModLoading
// file doesn't exist
if (validateFilesExist)
{
IFilePathLookup pathLookup = getFilePathLookup(mod.DirectoryPath);
string fileName = pathLookup.GetFilePath(mod.Manifest.EntryDll!);
if (!File.Exists(Path.Combine(mod.DirectoryPath, fileName)))
IFileLookup pathLookup = getFileLookup(mod.DirectoryPath);
FileInfo file = pathLookup.GetFile(mod.Manifest.EntryDll!);
if (!file.Exists)
{
mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist.");
continue;

View File

@ -405,7 +405,7 @@ namespace StardewModdingAPI.Framework
mods = mods.Where(p => !p.IsIgnored).ToArray();
// load mods
resolver.ValidateManifests(mods, Constants.ApiVersion, toolkit.GetUpdateUrl, getFilePathLookup: this.GetFilePathLookup);
resolver.ValidateManifests(mods, Constants.ApiVersion, toolkit.GetUpdateUrl, getFileLookup: this.GetFileLookup);
mods = resolver.ProcessDependencies(mods, modDatabase).ToArray();
this.LoadMods(mods, this.Toolkit.JsonHelper, this.ContentCore, modDatabase);
@ -1253,7 +1253,7 @@ namespace StardewModdingAPI.Framework
onLoadingFirstAsset: this.InitializeBeforeFirstAssetLoaded,
onAssetLoaded: this.OnAssetLoaded,
onAssetsInvalidated: this.OnAssetsInvalidated,
getFilePathLookup: this.GetFilePathLookup,
getFileLookup: this.GetFileLookup,
requestAssetOperations: this.RequestAssetOperations
);
if (this.ContentCore.Language != this.Translator.LocaleEnum)
@ -1754,11 +1754,11 @@ namespace StardewModdingAPI.Framework
if (mod.IsContentPack)
{
IMonitor monitor = this.LogManager.GetMonitor(mod.DisplayName);
IFilePathLookup relativePathCache = this.GetFilePathLookup(mod.DirectoryPath);
IFileLookup fileLookup = this.GetFileLookup(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);
IModContentHelper modContentHelper = new ModContentHelper(this.ContentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
TranslationHelper translationHelper = new(mod, contentCore.GetLocale(), contentCore.Language);
IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, modContentHelper, translationHelper, jsonHelper, relativePathCache);
IContentPack contentPack = new ContentPack(mod.DirectoryPath, manifest, modContentHelper, translationHelper, jsonHelper, fileLookup);
mod.SetMod(contentPack, monitor, translationHelper);
this.ModRegistry.Add(mod);
@ -1771,16 +1771,13 @@ namespace StardewModdingAPI.Framework
else
{
// get mod info
string assemblyPath = Path.Combine(
mod.DirectoryPath,
this.GetFilePathLookup(mod.DirectoryPath).GetFilePath(manifest.EntryDll!)
);
FileInfo assemblyFile = this.GetFileLookup(mod.DirectoryPath).GetFile(manifest.EntryDll!);
// load mod
Assembly modAssembly;
try
{
modAssembly = assemblyLoader.Load(mod, assemblyPath, assumeCompatible: mod.DataRecord?.Status == ModStatus.AssumeCompatible);
modAssembly = assemblyLoader.Load(mod, assemblyFile, assumeCompatible: mod.DataRecord?.Status == ModStatus.AssumeCompatible);
this.ModRegistry.TrackAssemblies(mod, modAssembly);
}
catch (IncompatibleInstructionException) // details already in trace logs
@ -1799,7 +1796,7 @@ namespace StardewModdingAPI.Framework
catch (Exception ex)
{
errorReasonPhrase = "its DLL couldn't be loaded.";
if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyPath))
if (ex is BadImageFormatException && !EnvironmentUtility.Is64BitAssembly(assemblyFile.FullName))
errorReasonPhrase = "it needs to be updated for 64-bit mode.";
errorDetails = $"Error: {ex.GetLogSummary()}";
@ -1837,12 +1834,11 @@ namespace StardewModdingAPI.Framework
{
IModEvents events = new ModEvents(mod, this.EventManager);
ICommandHelper commandHelper = new CommandHelper(mod, this.CommandManager);
IFilePathLookup relativePathLookup = this.GetFilePathLookup(mod.DirectoryPath);
#pragma warning disable CS0612 // deprecated code
ContentHelper contentHelper = new(contentCore, mod.DirectoryPath, mod, monitor, this.Reflection);
#pragma warning restore CS0612
GameContentHelper gameContentHelper = new(contentCore, mod, mod.DisplayName, monitor, this.Reflection);
IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), relativePathLookup, this.Reflection);
IModContentHelper modContentHelper = new ModContentHelper(contentCore, mod.DirectoryPath, mod, mod.DisplayName, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
IContentPackHelper contentPackHelper = new ContentPackHelper(
mod: mod,
contentPacks: new Lazy<IContentPack[]>(GetContentPacks),
@ -1896,13 +1892,13 @@ namespace StardewModdingAPI.Framework
// create mod helpers
IMonitor packMonitor = this.LogManager.GetMonitor(packManifest.Name);
IFilePathLookup relativePathCache = this.GetFilePathLookup(packDirPath);
GameContentHelper gameContentHelper = new(contentCore, fakeMod, packManifest.Name, packMonitor, this.Reflection);
IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), relativePathCache, this.Reflection);
IModContentHelper packContentHelper = new ModContentHelper(contentCore, packDirPath, fakeMod, packManifest.Name, gameContentHelper.GetUnderlyingContentManager(), this.Reflection);
TranslationHelper packTranslationHelper = new(fakeMod, contentCore.GetLocale(), contentCore.Language);
// add content pack
ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, relativePathCache);
IFileLookup fileLookup = this.GetFileLookup(packDirPath);
ContentPack contentPack = new(packDirPath, packManifest, packContentHelper, packTranslationHelper, this.Toolkit.JsonHelper, fileLookup);
this.ReloadTranslationsForTemporaryContentPack(parentMod, contentPack);
parentMod.FakeContentPacks.Add(new WeakReference<ContentPack>(contentPack));
@ -2061,13 +2057,13 @@ namespace StardewModdingAPI.Framework
return translations;
}
/// <summary>Get a file path lookup for the given directory.</summary>
/// <summary>Get a file lookup for the given directory.</summary>
/// <param name="rootDirectory">The root path to scan.</param>
private IFilePathLookup GetFilePathLookup(string rootDirectory)
private IFileLookup GetFileLookup(string rootDirectory)
{
return this.Settings.UseCaseInsensitivePaths
? CaseInsensitivePathLookup.GetCachedFor(rootDirectory)
: MinimalPathLookup.Instance;
? CaseInsensitiveFileLookup.GetCachedFor(rootDirectory)
: MinimalFileLookup.GetCachedFor(rootDirectory);
}
/// <summary>Get the map display device which applies SMAPI features like tile rotation to loaded maps.</summary>