From 625c41c0ea39bb2af37ece7865098cf2f6d38471 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 23 Aug 2020 18:45:54 -0400 Subject: move file for upcoming change --- .../Framework/LowLevelEnvironmentUtility.cs | 170 +++++++++++++++++++++ src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs | 170 --------------------- 2 files changed, 170 insertions(+), 170 deletions(-) create mode 100644 src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs delete mode 100644 src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs (limited to 'src/SMAPI.Toolkit') diff --git a/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs new file mode 100644 index 00000000..1e490448 --- /dev/null +++ b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs @@ -0,0 +1,170 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#if SMAPI_FOR_WINDOWS +using System.Management; +#endif +using System.Runtime.InteropServices; + +namespace StardewModdingAPI.Toolkit.Utilities +{ + /// Provides methods for fetching environment information. + public static class EnvironmentUtility + { + /********* + ** Fields + *********/ + /// The cached platform. + private static Platform? CachedPlatform; + + /// Get the OS name from the system uname command. + /// The buffer to fill with the resulting string. + [DllImport("libc")] + static extern int uname(IntPtr buffer); + + + /********* + ** Public methods + *********/ + /// Detect the current OS. + public static Platform DetectPlatform() + { + return EnvironmentUtility.CachedPlatform ??= EnvironmentUtility.DetectPlatformImpl(); + } + + + /// Get the human-readable OS name and version. + /// The current platform. + [SuppressMessage("ReSharper", "EmptyGeneralCatchClause", Justification = "Error suppressed deliberately to fallback to default behaviour.")] + public static string GetFriendlyPlatformName(Platform platform) + { +#if SMAPI_FOR_WINDOWS + try + { + return new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem") + .Get() + .Cast() + .Select(entry => entry.GetPropertyValue("Caption").ToString()) + .FirstOrDefault(); + } + catch { } +#endif + + string name = Environment.OSVersion.ToString(); + switch (platform) + { + case Platform.Android: + name = $"Android {name}"; + break; + + case Platform.Mac: + name = $"MacOS {name}"; + break; + } + return name; + } + + /// Get the name of the Stardew Valley executable. + /// The current platform. + public static string GetExecutableName(Platform platform) + { + return platform == Platform.Windows + ? "Stardew Valley.exe" + : "StardewValley.exe"; + } + + /// Get whether the platform uses Mono. + /// The current platform. + public static bool IsMono(this Platform platform) + { + return platform == Platform.Linux || platform == Platform.Mac; + } + + + /********* + ** Private methods + *********/ + /// Detect the current OS. + private static Platform DetectPlatformImpl() + { + switch (Environment.OSVersion.Platform) + { + case PlatformID.MacOSX: + return Platform.Mac; + + case PlatformID.Unix when EnvironmentUtility.IsRunningAndroid(): + return Platform.Android; + + case PlatformID.Unix when EnvironmentUtility.IsRunningMac(): + return Platform.Mac; + + case PlatformID.Unix: + return Platform.Linux; + + default: + return Platform.Windows; + } + } + + /// Detect whether the code is running on Android. + /// + /// This code is derived from https://stackoverflow.com/a/47521647/262123. It detects Android by calling the + /// getprop system command to check for an Android-specific property. + /// + private static bool IsRunningAndroid() + { + using Process process = new Process + { + StartInfo = + { + FileName = "getprop", + Arguments = "ro.build.user", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; + + try + { + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + return !string.IsNullOrWhiteSpace(output); + } + catch + { + return false; + } + } + + /// Detect whether the code is running on Mac. + /// + /// This code is derived from the Mono project (see System.Windows.Forms/System.Windows.Forms/XplatUI.cs). It detects Mac by calling the + /// uname system command and checking the response, which is always 'Darwin' for MacOS. + /// + private static bool IsRunningMac() + { + IntPtr buffer = IntPtr.Zero; + try + { + buffer = Marshal.AllocHGlobal(8192); + if (EnvironmentUtility.uname(buffer) == 0) + { + string os = Marshal.PtrToStringAnsi(buffer); + return os == "Darwin"; + } + return false; + } + catch + { + return false; // default to Linux + } + finally + { + if (buffer != IntPtr.Zero) + Marshal.FreeHGlobal(buffer); + } + } + } +} diff --git a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs deleted file mode 100644 index 1e490448..00000000 --- a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -#if SMAPI_FOR_WINDOWS -using System.Management; -#endif -using System.Runtime.InteropServices; - -namespace StardewModdingAPI.Toolkit.Utilities -{ - /// Provides methods for fetching environment information. - public static class EnvironmentUtility - { - /********* - ** Fields - *********/ - /// The cached platform. - private static Platform? CachedPlatform; - - /// Get the OS name from the system uname command. - /// The buffer to fill with the resulting string. - [DllImport("libc")] - static extern int uname(IntPtr buffer); - - - /********* - ** Public methods - *********/ - /// Detect the current OS. - public static Platform DetectPlatform() - { - return EnvironmentUtility.CachedPlatform ??= EnvironmentUtility.DetectPlatformImpl(); - } - - - /// Get the human-readable OS name and version. - /// The current platform. - [SuppressMessage("ReSharper", "EmptyGeneralCatchClause", Justification = "Error suppressed deliberately to fallback to default behaviour.")] - public static string GetFriendlyPlatformName(Platform platform) - { -#if SMAPI_FOR_WINDOWS - try - { - return new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem") - .Get() - .Cast() - .Select(entry => entry.GetPropertyValue("Caption").ToString()) - .FirstOrDefault(); - } - catch { } -#endif - - string name = Environment.OSVersion.ToString(); - switch (platform) - { - case Platform.Android: - name = $"Android {name}"; - break; - - case Platform.Mac: - name = $"MacOS {name}"; - break; - } - return name; - } - - /// Get the name of the Stardew Valley executable. - /// The current platform. - public static string GetExecutableName(Platform platform) - { - return platform == Platform.Windows - ? "Stardew Valley.exe" - : "StardewValley.exe"; - } - - /// Get whether the platform uses Mono. - /// The current platform. - public static bool IsMono(this Platform platform) - { - return platform == Platform.Linux || platform == Platform.Mac; - } - - - /********* - ** Private methods - *********/ - /// Detect the current OS. - private static Platform DetectPlatformImpl() - { - switch (Environment.OSVersion.Platform) - { - case PlatformID.MacOSX: - return Platform.Mac; - - case PlatformID.Unix when EnvironmentUtility.IsRunningAndroid(): - return Platform.Android; - - case PlatformID.Unix when EnvironmentUtility.IsRunningMac(): - return Platform.Mac; - - case PlatformID.Unix: - return Platform.Linux; - - default: - return Platform.Windows; - } - } - - /// Detect whether the code is running on Android. - /// - /// This code is derived from https://stackoverflow.com/a/47521647/262123. It detects Android by calling the - /// getprop system command to check for an Android-specific property. - /// - private static bool IsRunningAndroid() - { - using Process process = new Process - { - StartInfo = - { - FileName = "getprop", - Arguments = "ro.build.user", - RedirectStandardOutput = true, - UseShellExecute = false, - CreateNoWindow = true - } - }; - - try - { - process.Start(); - string output = process.StandardOutput.ReadToEnd(); - return !string.IsNullOrWhiteSpace(output); - } - catch - { - return false; - } - } - - /// Detect whether the code is running on Mac. - /// - /// This code is derived from the Mono project (see System.Windows.Forms/System.Windows.Forms/XplatUI.cs). It detects Mac by calling the - /// uname system command and checking the response, which is always 'Darwin' for MacOS. - /// - private static bool IsRunningMac() - { - IntPtr buffer = IntPtr.Zero; - try - { - buffer = Marshal.AllocHGlobal(8192); - if (EnvironmentUtility.uname(buffer) == 0) - { - string os = Marshal.PtrToStringAnsi(buffer); - return os == "Darwin"; - } - return false; - } - catch - { - return false; // default to Linux - } - finally - { - if (buffer != IntPtr.Zero) - Marshal.FreeHGlobal(buffer); - } - } - } -} -- cgit From 76c926c396092f02441a62937bfc5d437e582e57 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 23 Aug 2020 18:45:04 -0400 Subject: add EarlyConstants for constants needed before external DLLs are loaded --- .../Framework/LowLevelEnvironmentUtility.cs | 69 ++++++++++------------ src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs | 57 ++++++++++++++++++ 2 files changed, 88 insertions(+), 38 deletions(-) create mode 100644 src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs (limited to 'src/SMAPI.Toolkit') diff --git a/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs index 1e490448..b01d8b21 100644 --- a/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs +++ b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs @@ -6,18 +6,17 @@ using System.Linq; using System.Management; #endif using System.Runtime.InteropServices; +using StardewModdingAPI.Toolkit.Utilities; -namespace StardewModdingAPI.Toolkit.Utilities +namespace StardewModdingAPI.Toolkit.Framework { - /// Provides methods for fetching environment information. - public static class EnvironmentUtility + /// Provides low-level methods for fetching environment information. + /// This is used by the SMAPI core before the toolkit DLL is available; most code should use instead. + internal static class LowLevelEnvironmentUtility { /********* ** Fields *********/ - /// The cached platform. - private static Platform? CachedPlatform; - /// Get the OS name from the system uname command. /// The buffer to fill with the resulting string. [DllImport("libc")] @@ -28,16 +27,32 @@ namespace StardewModdingAPI.Toolkit.Utilities ** Public methods *********/ /// Detect the current OS. - public static Platform DetectPlatform() + public static string DetectPlatform() { - return EnvironmentUtility.CachedPlatform ??= EnvironmentUtility.DetectPlatformImpl(); + switch (Environment.OSVersion.Platform) + { + case PlatformID.MacOSX: + return nameof(Platform.Mac); + + case PlatformID.Unix when LowLevelEnvironmentUtility.IsRunningAndroid(): + return nameof(Platform.Android); + + case PlatformID.Unix when LowLevelEnvironmentUtility.IsRunningMac(): + return nameof(Platform.Mac); + + case PlatformID.Unix: + return nameof(Platform.Linux); + + default: + return nameof(Platform.Windows); + } } /// Get the human-readable OS name and version. /// The current platform. [SuppressMessage("ReSharper", "EmptyGeneralCatchClause", Justification = "Error suppressed deliberately to fallback to default behaviour.")] - public static string GetFriendlyPlatformName(Platform platform) + public static string GetFriendlyPlatformName(string platform) { #if SMAPI_FOR_WINDOWS try @@ -54,11 +69,11 @@ namespace StardewModdingAPI.Toolkit.Utilities string name = Environment.OSVersion.ToString(); switch (platform) { - case Platform.Android: + case nameof(Platform.Android): name = $"Android {name}"; break; - case Platform.Mac: + case nameof(Platform.Mac): name = $"MacOS {name}"; break; } @@ -67,46 +82,24 @@ namespace StardewModdingAPI.Toolkit.Utilities /// Get the name of the Stardew Valley executable. /// The current platform. - public static string GetExecutableName(Platform platform) + public static string GetExecutableName(string platform) { - return platform == Platform.Windows + return platform == nameof(Platform.Windows) ? "Stardew Valley.exe" : "StardewValley.exe"; } /// Get whether the platform uses Mono. /// The current platform. - public static bool IsMono(this Platform platform) + public static bool IsMono(string platform) { - return platform == Platform.Linux || platform == Platform.Mac; + return platform == nameof(Platform.Linux) || platform == nameof(Platform.Mac); } /********* ** Private methods *********/ - /// Detect the current OS. - private static Platform DetectPlatformImpl() - { - switch (Environment.OSVersion.Platform) - { - case PlatformID.MacOSX: - return Platform.Mac; - - case PlatformID.Unix when EnvironmentUtility.IsRunningAndroid(): - return Platform.Android; - - case PlatformID.Unix when EnvironmentUtility.IsRunningMac(): - return Platform.Mac; - - case PlatformID.Unix: - return Platform.Linux; - - default: - return Platform.Windows; - } - } - /// Detect whether the code is running on Android. /// /// This code is derived from https://stackoverflow.com/a/47521647/262123. It detects Android by calling the @@ -149,7 +142,7 @@ namespace StardewModdingAPI.Toolkit.Utilities try { buffer = Marshal.AllocHGlobal(8192); - if (EnvironmentUtility.uname(buffer) == 0) + if (LowLevelEnvironmentUtility.uname(buffer) == 0) { string os = Marshal.PtrToStringAnsi(buffer); return os == "Darwin"; diff --git a/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs new file mode 100644 index 00000000..4ef578f7 --- /dev/null +++ b/src/SMAPI.Toolkit/Utilities/EnvironmentUtility.cs @@ -0,0 +1,57 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using StardewModdingAPI.Toolkit.Framework; + +namespace StardewModdingAPI.Toolkit.Utilities +{ + /// Provides methods for fetching environment information. + public static class EnvironmentUtility + { + /********* + ** Fields + *********/ + /// The cached platform. + private static Platform? CachedPlatform; + + + /********* + ** Public methods + *********/ + /// Detect the current OS. + public static Platform DetectPlatform() + { + Platform? platform = EnvironmentUtility.CachedPlatform; + + if (platform == null) + { + string rawPlatform = LowLevelEnvironmentUtility.DetectPlatform(); + EnvironmentUtility.CachedPlatform = platform = (Platform)Enum.Parse(typeof(Platform), rawPlatform, ignoreCase: true); + } + + return platform.Value; + } + + + /// Get the human-readable OS name and version. + /// The current platform. + [SuppressMessage("ReSharper", "EmptyGeneralCatchClause", Justification = "Error suppressed deliberately to fallback to default behaviour.")] + public static string GetFriendlyPlatformName(Platform platform) + { + return LowLevelEnvironmentUtility.GetFriendlyPlatformName(platform.ToString()); + } + + /// Get the name of the Stardew Valley executable. + /// The current platform. + public static string GetExecutableName(Platform platform) + { + return LowLevelEnvironmentUtility.GetExecutableName(platform.ToString()); + } + + /// Get whether the platform uses Mono. + /// The current platform. + public static bool IsMono(this Platform platform) + { + return LowLevelEnvironmentUtility.IsMono(platform.ToString()); + } + } +} -- cgit From 828be405e11dd8bc7f8a3692d2c74517734f67a5 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 30 Aug 2020 22:53:19 -0400 Subject: use inheritdoc --- src/SMAPI.Toolkit/SemanticVersion.cs | 47 ++++++++++++------------------------ 1 file changed, 16 insertions(+), 31 deletions(-) (limited to 'src/SMAPI.Toolkit') diff --git a/src/SMAPI.Toolkit/SemanticVersion.cs b/src/SMAPI.Toolkit/SemanticVersion.cs index 1a76bec3..0f341665 100644 --- a/src/SMAPI.Toolkit/SemanticVersion.cs +++ b/src/SMAPI.Toolkit/SemanticVersion.cs @@ -25,22 +25,22 @@ namespace StardewModdingAPI.Toolkit /********* ** Accessors *********/ - /// The major version incremented for major API changes. + /// public int MajorVersion { get; } - /// The minor version incremented for backwards-compatible changes. + /// public int MinorVersion { get; } - /// The patch version for backwards-compatible bug fixes. + /// public int PatchVersion { get; } /// The platform release. This is a non-standard semver extension used by Stardew Valley on ported platforms to represent platform-specific patches to a ported version, represented as a fourth number in the version string. public int PlatformRelease { get; } - /// An optional prerelease tag. + /// public string PrereleaseTag { get; } - /// Optional build metadata. This is ignored when determining version precedence. + /// public string BuildMetadata { get; } @@ -103,9 +103,7 @@ namespace StardewModdingAPI.Toolkit this.AssertValid(); } - /// Get an integer indicating whether this version precedes (less than 0), supersedes (more than 0), or is equivalent to (0) the specified version. - /// The version to compare with this instance. - /// The value is null. + /// public int CompareTo(ISemanticVersion other) { if (other == null) @@ -113,68 +111,55 @@ namespace StardewModdingAPI.Toolkit return this.CompareTo(other.MajorVersion, other.MinorVersion, other.PatchVersion, (other as SemanticVersion)?.PlatformRelease ?? 0, other.PrereleaseTag); } - /// Indicates whether the current object is equal to another object of the same type. - /// true if the current object is equal to the parameter; otherwise, false. - /// An object to compare with this object. + /// public bool Equals(ISemanticVersion other) { return other != null && this.CompareTo(other) == 0; } - /// Whether this is a prerelease version. + /// public bool IsPrerelease() { return !string.IsNullOrWhiteSpace(this.PrereleaseTag); } - /// Get whether this version is older than the specified version. - /// The version to compare with this instance. + /// public bool IsOlderThan(ISemanticVersion other) { return this.CompareTo(other) < 0; } - /// Get whether this version is older than the specified version. - /// The version to compare with this instance. - /// The specified version is not a valid semantic version. + /// public bool IsOlderThan(string other) { return this.IsOlderThan(new SemanticVersion(other, allowNonStandard: true)); } - /// Get whether this version is newer than the specified version. - /// The version to compare with this instance. + /// public bool IsNewerThan(ISemanticVersion other) { return this.CompareTo(other) > 0; } - /// Get whether this version is newer than the specified version. - /// The version to compare with this instance. - /// The specified version is not a valid semantic version. + /// public bool IsNewerThan(string other) { return this.IsNewerThan(new SemanticVersion(other, allowNonStandard: true)); } - /// Get whether this version is between two specified versions (inclusively). - /// The minimum version. - /// The maximum version. + /// public bool IsBetween(ISemanticVersion min, ISemanticVersion max) { return this.CompareTo(min) >= 0 && this.CompareTo(max) <= 0; } - /// Get whether this version is between two specified versions (inclusively). - /// The minimum version. - /// The maximum version. - /// One of the specified versions is not a valid semantic version. + /// public bool IsBetween(string min, string max) { return this.IsBetween(new SemanticVersion(min, allowNonStandard: true), new SemanticVersion(max, allowNonStandard: true)); } - /// Get a string representation of the version. + /// public override string ToString() { string version = $"{this.MajorVersion}.{this.MinorVersion}.{this.PatchVersion}"; @@ -187,7 +172,7 @@ namespace StardewModdingAPI.Toolkit return version; } - /// Whether the version uses non-standard extensions, like four-part game versions on some platforms. + /// public bool IsNonStandard() { return this.PlatformRelease != 0; -- cgit From 5d1c77884f6686a59f121639dc177b7095e8c477 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 5 Sep 2020 13:37:40 -0400 Subject: add unit tests for PathUtilities, fix some edge cases --- src/SMAPI.Toolkit/Utilities/PathUtilities.cs | 43 ++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 5 deletions(-) (limited to 'src/SMAPI.Toolkit') diff --git a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs index e9d71747..34940d4f 100644 --- a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs +++ b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs @@ -9,6 +9,13 @@ namespace StardewModdingAPI.Toolkit.Utilities /// Provides utilities for normalizing file paths. public static class PathUtilities { + /********* + ** Fields + *********/ + /// The root prefix for a Windows UNC path. + private const string WindowsUncRoot = @"\\"; + + /********* ** Accessors *********/ @@ -25,6 +32,7 @@ namespace StardewModdingAPI.Toolkit.Utilities /// Get the segments from a path (e.g. /usr/bin/example => usr, bin, and example). /// The path to split. /// The number of segments to match. Any additional segments will be merged into the last returned part. + [Pure] public static string[] GetSegments(string path, int? limit = null) { return limit.HasValue @@ -37,16 +45,28 @@ namespace StardewModdingAPI.Toolkit.Utilities [Pure] public static string NormalizePathSeparators(string path) { - string[] parts = PathUtilities.GetSegments(path); - string normalized = string.Join(PathUtilities.PreferredPathSeparator, parts); - if (path.StartsWith(PathUtilities.PreferredPathSeparator)) - normalized = PathUtilities.PreferredPathSeparator + normalized; // keep root slash + string normalized = string.Join(PathUtilities.PreferredPathSeparator, PathUtilities.GetSegments(path)); + + // keep root +#if SMAPI_FOR_WINDOWS + if (path.StartsWith(PathUtilities.WindowsUncRoot)) + normalized = PathUtilities.WindowsUncRoot + normalized; + else +#endif + if (path.StartsWith(PathUtilities.PreferredPathSeparator) || path.StartsWith(PathUtilities.WindowsUncRoot)) + normalized = PathUtilities.PreferredPathSeparator + normalized; + return normalized; } - /// Get a directory or file path relative to a given source path. + /// Get a directory or file path relative to a given source path. If no relative path is possible (e.g. the paths are on different drives), an absolute path is returned. /// The source folder path. /// The target folder or file path. + /// + /// + /// NOTE: this is a heuristic implementation that works in the cases SMAPI needs it for, but it doesn't handle all edge cases (e.g. case-sensitivity on Linux, or traversing between UNC paths on Windows). This should be replaced with the more comprehensive Path.GetRelativePath if the game ever migrates to .NET Core. + /// + /// [Pure] public static string GetRelativePath(string sourceDir, string targetPath) { @@ -58,13 +78,25 @@ namespace StardewModdingAPI.Toolkit.Utilities // get relative path string relative = PathUtilities.NormalizePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString())); + + // set empty path to './' if (relative == "") relative = "./"; + + // fix root + if (relative.StartsWith("file:") && !targetPath.Contains("file:")) + { + relative = relative.Substring("file:".Length); + if (targetPath.StartsWith(PathUtilities.WindowsUncRoot) && !relative.StartsWith(PathUtilities.WindowsUncRoot)) + relative = PathUtilities.WindowsUncRoot + relative.TrimStart('\\'); + } + return relative; } /// Get whether a path is relative and doesn't try to climb out of its containing folder (e.g. doesn't contain ../). /// The path to check. + [Pure] public static bool IsSafeRelativePath(string path) { if (string.IsNullOrWhiteSpace(path)) @@ -77,6 +109,7 @@ namespace StardewModdingAPI.Toolkit.Utilities /// Get whether a string is a valid 'slug', containing only basic characters that are safe in all contexts (e.g. filenames, URLs, etc). /// The string to check. + [Pure] public static bool IsSlug(string str) { return !Regex.IsMatch(str, "[^a-z0-9_.-]", RegexOptions.IgnoreCase); -- cgit From be1df8e7050ff5872799f6bee7f8cb419d7a3f38 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 5 Sep 2020 14:51:52 -0400 Subject: simplify path separator normalization It no longer tries to clean up the path (e.g. "path/to///file/" => "path/to/file"), which means it can more intuitively handle cases like this: asset.AssetName.StartsWith(PathUtilities.NormalizePathSeparators("Characters/Dialogue/")) --- src/SMAPI.Toolkit/Utilities/PathUtilities.cs | 32 +++++++++++----------------- 1 file changed, 13 insertions(+), 19 deletions(-) (limited to 'src/SMAPI.Toolkit') diff --git a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs index 34940d4f..bd5fafbc 100644 --- a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs +++ b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs @@ -45,18 +45,10 @@ namespace StardewModdingAPI.Toolkit.Utilities [Pure] public static string NormalizePathSeparators(string path) { - string normalized = string.Join(PathUtilities.PreferredPathSeparator, PathUtilities.GetSegments(path)); - - // keep root -#if SMAPI_FOR_WINDOWS - if (path.StartsWith(PathUtilities.WindowsUncRoot)) - normalized = PathUtilities.WindowsUncRoot + normalized; - else -#endif - if (path.StartsWith(PathUtilities.PreferredPathSeparator) || path.StartsWith(PathUtilities.WindowsUncRoot)) - normalized = PathUtilities.PreferredPathSeparator + normalized; + if (string.IsNullOrWhiteSpace(path)) + return path; - return normalized; + return string.Join(PathUtilities.PreferredPathSeparator, path.Split(PathUtilities.PossiblePathSeparators)); } /// Get a directory or file path relative to a given source path. If no relative path is possible (e.g. the paths are on different drives), an absolute path is returned. @@ -79,16 +71,18 @@ namespace StardewModdingAPI.Toolkit.Utilities // get relative path string relative = PathUtilities.NormalizePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString())); - // set empty path to './' + // normalize if (relative == "") - relative = "./"; - - // fix root - if (relative.StartsWith("file:") && !targetPath.Contains("file:")) + relative = "."; + else { - relative = relative.Substring("file:".Length); - if (targetPath.StartsWith(PathUtilities.WindowsUncRoot) && !relative.StartsWith(PathUtilities.WindowsUncRoot)) - relative = PathUtilities.WindowsUncRoot + relative.TrimStart('\\'); + // trim trailing slash from URL + if (relative.EndsWith(PathUtilities.PreferredPathSeparator)) + relative = relative.Substring(0, relative.Length - PathUtilities.PreferredPathSeparator.Length); + + // fix root + if (relative.StartsWith("file:") && !targetPath.Contains("file:")) + relative = relative.Substring("file:".Length); } return relative; -- cgit