summaryrefslogtreecommitdiff
path: root/src/StardewModdingAPI.Toolkit
diff options
context:
space:
mode:
Diffstat (limited to 'src/StardewModdingAPI.Toolkit')
-rw-r--r--src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityClient.cs161
-rw-r--r--src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityEntry.cs36
-rw-r--r--src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityStatus.cs27
-rw-r--r--src/StardewModdingAPI.Toolkit/ISemanticVersion.cs46
-rw-r--r--src/StardewModdingAPI.Toolkit/ModToolkit.cs33
-rw-r--r--src/StardewModdingAPI.Toolkit/Properties/AssemblyInfo.cs10
-rw-r--r--src/StardewModdingAPI.Toolkit/SemanticVersion.cs239
-rw-r--r--src/StardewModdingAPI.Toolkit/StardewModdingAPI.Toolkit.csproj20
-rw-r--r--src/StardewModdingAPI.Toolkit/Utilities/PathUtilities.cs65
9 files changed, 637 insertions, 0 deletions
diff --git a/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityClient.cs b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityClient.cs
new file mode 100644
index 00000000..d0da42df
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityClient.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading.Tasks;
+using HtmlAgilityPack;
+using Pathoschild.Http.Client;
+
+namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki
+{
+ /// <summary>An HTTP client for fetching mod metadata from the wiki compatibility list.</summary>
+ public class WikiCompatibilityClient : IDisposable
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The underlying HTTP client.</summary>
+ private readonly IClient Client;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="userAgent">The user agent for the wiki API.</param>
+ /// <param name="baseUrl">The base URL for the wiki API.</param>
+ public WikiCompatibilityClient(string userAgent, string baseUrl = "https://stardewvalleywiki.com/mediawiki/api.php")
+ {
+ this.Client = new FluentClient(baseUrl).SetUserAgent(userAgent);
+ }
+
+ /// <summary>Fetch mod compatibility entries.</summary>
+ public async Task<WikiCompatibilityEntry[]> FetchAsync()
+ {
+ // fetch HTML
+ ResponseModel response = await this.Client
+ .GetAsync("")
+ .WithArguments(new
+ {
+ action = "parse",
+ page = "Modding:SMAPI_compatibility",
+ format = "json"
+ })
+ .As<ResponseModel>();
+ string html = response.Parse.Text["*"];
+
+ // parse HTML
+ var doc = new HtmlDocument();
+ doc.LoadHtml(html);
+
+ // find mod entries
+ HtmlNodeCollection modNodes = doc.DocumentNode.SelectNodes("table[@id='mod-list']//tr[@class='mod']");
+ if (modNodes == null)
+ throw new InvalidOperationException("Can't parse wiki compatibility list, no mods found.");
+
+ // parse
+ return this.ParseEntries(modNodes).ToArray();
+ }
+
+ /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
+ public void Dispose()
+ {
+ this.Client?.Dispose();
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Parse valid mod compatibility entries.</summary>
+ /// <param name="nodes">The HTML compatibility entries.</param>
+ private IEnumerable<WikiCompatibilityEntry> ParseEntries(IEnumerable<HtmlNode> nodes)
+ {
+ foreach (HtmlNode node in nodes)
+ {
+ // parse status
+ WikiCompatibilityStatus status;
+ {
+ string rawStatus = node.GetAttributeValue("data-status", null);
+ if (rawStatus == null)
+ continue; // not a mod node?
+ if (!Enum.TryParse(rawStatus, true, out status))
+ throw new InvalidOperationException($"Unknown status '{rawStatus}' when parsing compatibility list.");
+ }
+
+ // parse unofficial version
+ ISemanticVersion unofficialVersion = null;
+ {
+ string rawUnofficialVersion = node.GetAttributeValue("data-unofficial-version", null);
+ SemanticVersion.TryParse(rawUnofficialVersion, out unofficialVersion);
+ }
+
+ // parse other fields
+ string name = node.Descendants("td").FirstOrDefault()?.InnerText?.Trim();
+ string summary = node.Descendants("td").FirstOrDefault(p => p.GetAttributeValue("class", null) == "summary")?.InnerText.Trim();
+ string[] ids = this.GetAttribute(node, "data-id")?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray() ?? new string[0];
+ int? nexusID = this.GetNullableIntAttribute(node, "data-nexus-id");
+ int? chucklefishID = this.GetNullableIntAttribute(node, "data-chucklefish-id");
+ string githubRepo = this.GetAttribute(node, "data-github");
+ string customSourceUrl = this.GetAttribute(node, "data-custom-source");
+ string customUrl = this.GetAttribute(node, "data-custom-url");
+
+ // yield model
+ yield return new WikiCompatibilityEntry
+ {
+ ID = ids,
+ Name = name,
+ Status = status,
+ NexusID = nexusID,
+ ChucklefishID = chucklefishID,
+ GitHubRepo = githubRepo,
+ CustomSourceUrl = customSourceUrl,
+ CustomUrl = customUrl,
+ UnofficialVersion = unofficialVersion,
+ Summary = summary
+ };
+ }
+ }
+
+ /// <summary>Get a nullable integer attribute value.</summary>
+ /// <param name="node">The HTML node.</param>
+ /// <param name="attributeName">The attribute name.</param>
+ private int? GetNullableIntAttribute(HtmlNode node, string attributeName)
+ {
+ string raw = this.GetAttribute(node, attributeName);
+ if (raw != null && int.TryParse(raw, out int value))
+ return value;
+ return null;
+ }
+
+ /// <summary>Get a strings attribute value.</summary>
+ /// <param name="node">The HTML node.</param>
+ /// <param name="attributeName">The attribute name.</param>
+ private string GetAttribute(HtmlNode node, string attributeName)
+ {
+ string raw = node.GetAttributeValue(attributeName, null);
+ if (raw != null)
+ raw = HtmlEntity.DeEntitize(raw);
+ return raw;
+ }
+
+ /// <summary>The response model for the MediaWiki parse API.</summary>
+ [SuppressMessage("ReSharper", "ClassNeverInstantiated.Local")]
+ [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
+ private class ResponseModel
+ {
+ /// <summary>The parse API results.</summary>
+ public ResponseParseModel Parse { get; set; }
+ }
+
+ /// <summary>The inner response model for the MediaWiki parse API.</summary>
+ [SuppressMessage("ReSharper", "ClassNeverInstantiated.Local")]
+ [SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
+ [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
+ private class ResponseParseModel
+ {
+ /// <summary>The parsed text.</summary>
+ public IDictionary<string, string> Text { get; set; }
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityEntry.cs b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityEntry.cs
new file mode 100644
index 00000000..8bc66e20
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityEntry.cs
@@ -0,0 +1,36 @@
+namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki
+{
+ /// <summary>An entry in the mod compatibility list.</summary>
+ public class WikiCompatibilityEntry
+ {
+ /// <summary>The mod's unique ID. A mod may have multiple current IDs in rare cases (e.g. due to parallel releases or unofficial updates).</summary>
+ public string[] ID { get; set; }
+
+ /// <summary>The mod's display name.</summary>
+ public string Name { get; set; }
+
+ /// <summary>The mod ID on Nexus.</summary>
+ public int? NexusID { get; set; }
+
+ /// <summary>The mod ID in the Chucklefish mod repo.</summary>
+ public int? ChucklefishID { get; set; }
+
+ /// <summary>The GitHub repository in the form 'owner/repo'.</summary>
+ public string GitHubRepo { get; set; }
+
+ /// <summary>The URL to a non-GitHub source repo.</summary>
+ public string CustomSourceUrl { get; set; }
+
+ /// <summary>The custom mod page URL (if applicable).</summary>
+ public string CustomUrl { get; set; }
+
+ /// <summary>The version of the latest unofficial update, if applicable.</summary>
+ public ISemanticVersion UnofficialVersion { get; set; }
+
+ /// <summary>The compatibility status.</summary>
+ public WikiCompatibilityStatus Status { get; set; }
+
+ /// <summary>The human-readable summary of the compatibility status or workaround, without HTML formatitng.</summary>
+ public string Summary { get; set; }
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityStatus.cs b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityStatus.cs
new file mode 100644
index 00000000..a1d2dfae
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/Framework/Clients/Wiki/WikiCompatibilityStatus.cs
@@ -0,0 +1,27 @@
+namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki
+{
+ /// <summary>The compatibility status for a mod.</summary>
+ public enum WikiCompatibilityStatus
+ {
+ /// <summary>The mod is compatible.</summary>
+ Ok = 0,
+
+ /// <summary>The mod is compatible if you use an optional official download.</summary>
+ Optional = 1,
+
+ /// <summary>The mod is compatible if you use an unofficial update.</summary>
+ Unofficial = 2,
+
+ /// <summary>The mod isn't compatible, but the player can fix it or there's a good alternative.</summary>
+ Workaround = 3,
+
+ /// <summary>The mod isn't compatible.</summary>
+ Broken = 4,
+
+ /// <summary>The mod is no longer maintained by the author, and an unofficial update or continuation is unlikely.</summary>
+ Abandoned = 5,
+
+ /// <summary>The mod is no longer needed and should be removed.</summary>
+ Obsolete = 6
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/ISemanticVersion.cs b/src/StardewModdingAPI.Toolkit/ISemanticVersion.cs
new file mode 100644
index 00000000..ca62d393
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/ISemanticVersion.cs
@@ -0,0 +1,46 @@
+using System;
+
+namespace StardewModdingAPI.Toolkit
+{
+ /// <summary>A semantic version with an optional release tag.</summary>
+ public interface ISemanticVersion : IComparable<ISemanticVersion>, IEquatable<ISemanticVersion>
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The major version incremented for major API changes.</summary>
+ int Major { get; }
+
+ /// <summary>The minor version incremented for backwards-compatible changes.</summary>
+ int Minor { get; }
+
+ /// <summary>The patch version for backwards-compatible bug fixes.</summary>
+ int Patch { get; }
+
+ /// <summary>An optional prerelease tag.</summary>
+ string Tag { get; }
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether this is a pre-release version.</summary>
+ bool IsPrerelease();
+
+ /// <summary>Get whether this version is older than the specified version.</summary>
+ /// <param name="other">The version to compare with this instance.</param>
+ bool IsOlderThan(ISemanticVersion other);
+
+ /// <summary>Get whether this version is newer than the specified version.</summary>
+ /// <param name="other">The version to compare with this instance.</param>
+ bool IsNewerThan(ISemanticVersion other);
+
+ /// <summary>Get whether this version is between two specified versions (inclusively).</summary>
+ /// <param name="min">The minimum version.</param>
+ /// <param name="max">The maximum version.</param>
+ bool IsBetween(ISemanticVersion min, ISemanticVersion max);
+
+ /// <summary>Get a string representation of the version.</summary>
+ string ToString();
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/ModToolkit.cs b/src/StardewModdingAPI.Toolkit/ModToolkit.cs
new file mode 100644
index 00000000..6136186e
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/ModToolkit.cs
@@ -0,0 +1,33 @@
+using System.Threading.Tasks;
+using StardewModdingAPI.Toolkit.Framework.Clients.Wiki;
+
+namespace StardewModdingAPI.Toolkit
+{
+ /// <summary>A convenience wrapper for the various tools.</summary>
+ public class ModToolkit
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The default HTTP user agent for the toolkit.</summary>
+ private readonly string UserAgent;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public ModToolkit()
+ {
+ ISemanticVersion version = new SemanticVersion(this.GetType().Assembly.GetName().Version);
+ this.UserAgent = $"SMAPI Mod Handler Toolkit/{version}";
+ }
+
+ /// <summary>Extract mod metadata from the wiki compatibility list.</summary>
+ public async Task<WikiCompatibilityEntry[]> GetWikiCompatibilityListAsync()
+ {
+ var client = new WikiCompatibilityClient(this.UserAgent);
+ return await client.FetchAsync();
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/Properties/AssemblyInfo.cs b/src/StardewModdingAPI.Toolkit/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..22dcdd96
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/Properties/AssemblyInfo.cs
@@ -0,0 +1,10 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+[assembly: AssemblyTitle("SMAPI.Toolkit")]
+[assembly: AssemblyDescription("A library which encapsulates mod-handling logic for mod managers and tools. Not intended for use by mods.")]
+[assembly: AssemblyProduct("SMAPI Toolkit")]
+[assembly: AssemblyVersion("0.1.0")]
+[assembly: AssemblyFileVersion("0.1.0")]
+[assembly: InternalsVisibleTo("StardewModdingAPI")]
+[assembly: InternalsVisibleTo("StardewModdingAPI.Web")]
diff --git a/src/StardewModdingAPI.Toolkit/SemanticVersion.cs b/src/StardewModdingAPI.Toolkit/SemanticVersion.cs
new file mode 100644
index 00000000..bd85f990
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/SemanticVersion.cs
@@ -0,0 +1,239 @@
+using System;
+using System.Text.RegularExpressions;
+
+namespace StardewModdingAPI.Toolkit
+{
+ /// <summary>A semantic version with an optional release tag.</summary>
+ /// <remarks>The implementation is defined by Semantic Version 2.0 (http://semver.org/).</remarks>
+ public class SemanticVersion : ISemanticVersion
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>A regex pattern matching a version within a larger string.</summary>
+ internal const string UnboundedVersionPattern = @"(?>(?<major>0|[1-9]\d*))\.(?>(?<minor>0|[1-9]\d*))(?>(?:\.(?<patch>0|[1-9]\d*))?)(?:-(?<prerelease>(?>[a-z0-9]+[\-\.]?)+))?";
+
+ /// <summary>A regular expression matching a semantic version string.</summary>
+ /// <remarks>
+ /// This pattern is derived from the BNF documentation in the <a href="https://github.com/mojombo/semver">semver repo</a>,
+ /// with three important deviations intended to support Stardew Valley mod conventions:
+ /// - allows short-form "x.y" versions;
+ /// - allows hyphens in prerelease tags as synonyms for dots (like "-unofficial-update.3");
+ /// - doesn't allow '+build' suffixes.
+ /// </remarks>
+ internal static readonly Regex Regex = new Regex($@"^{SemanticVersion.UnboundedVersionPattern}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The major version incremented for major API changes.</summary>
+ public int Major { get; }
+
+ /// <summary>The minor version incremented for backwards-compatible changes.</summary>
+ public int Minor { get; }
+
+ /// <summary>The patch version for backwards-compatible bug fixes.</summary>
+ public int Patch { get; }
+
+ /// <summary>An optional prerelease tag.</summary>
+ public string Tag { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="major">The major version incremented for major API changes.</param>
+ /// <param name="minor">The minor version incremented for backwards-compatible changes.</param>
+ /// <param name="patch">The patch version for backwards-compatible fixes.</param>
+ /// <param name="tag">An optional prerelease tag.</param>
+ public SemanticVersion(int major, int minor, int patch, string tag = null)
+ {
+ this.Major = major;
+ this.Minor = minor;
+ this.Patch = patch;
+ this.Tag = this.GetNormalisedTag(tag);
+ }
+
+ /// <summary>Construct an instance.</summary>
+ /// <param name="version">The assembly version.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="version"/> is null.</exception>
+ public SemanticVersion(Version version)
+ {
+ if (version == null)
+ throw new ArgumentNullException(nameof(version), "The input version can't be null.");
+
+ this.Major = version.Major;
+ this.Minor = version.Minor;
+ this.Patch = version.Build;
+ }
+
+ /// <summary>Construct an instance.</summary>
+ /// <param name="version">The semantic version string.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="version"/> is null.</exception>
+ /// <exception cref="FormatException">The <paramref name="version"/> is not a valid semantic version.</exception>
+ public SemanticVersion(string version)
+ {
+ // parse
+ if (version == null)
+ throw new ArgumentNullException(nameof(version), "The input version string can't be null.");
+ var match = SemanticVersion.Regex.Match(version.Trim());
+ if (!match.Success)
+ throw new FormatException($"The input '{version}' isn't a valid semantic version.");
+
+ // initialise
+ this.Major = int.Parse(match.Groups["major"].Value);
+ this.Minor = match.Groups["minor"].Success ? int.Parse(match.Groups["minor"].Value) : 0;
+ this.Patch = match.Groups["patch"].Success ? int.Parse(match.Groups["patch"].Value) : 0;
+ this.Tag = match.Groups["prerelease"].Success ? this.GetNormalisedTag(match.Groups["prerelease"].Value) : null;
+ }
+
+ /// <summary>Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.</summary>
+ /// <param name="other">The version to compare with this instance.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="other"/> value is null.</exception>
+ public int CompareTo(ISemanticVersion other)
+ {
+ if (other == null)
+ throw new ArgumentNullException(nameof(other));
+ return this.CompareTo(other.Major, other.Minor, other.Patch, other.Tag);
+ }
+
+ /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
+ /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
+ /// <param name="other">An object to compare with this object.</param>
+ public bool Equals(ISemanticVersion other)
+ {
+ return other != null && this.CompareTo(other) == 0;
+ }
+
+ /// <summary>Whether this is a pre-release version.</summary>
+ public bool IsPrerelease()
+ {
+ return !string.IsNullOrWhiteSpace(this.Tag);
+ }
+
+ /// <summary>Get whether this version is older than the specified version.</summary>
+ /// <param name="other">The version to compare with this instance.</param>
+ public bool IsOlderThan(ISemanticVersion other)
+ {
+ return this.CompareTo(other) < 0;
+ }
+
+ /// <summary>Get whether this version is newer than the specified version.</summary>
+ /// <param name="other">The version to compare with this instance.</param>
+ public bool IsNewerThan(ISemanticVersion other)
+ {
+ return this.CompareTo(other) > 0;
+ }
+
+ /// <summary>Get whether this version is between two specified versions (inclusively).</summary>
+ /// <param name="min">The minimum version.</param>
+ /// <param name="max">The maximum version.</param>
+ public bool IsBetween(ISemanticVersion min, ISemanticVersion max)
+ {
+ return this.CompareTo(min) >= 0 && this.CompareTo(max) <= 0;
+ }
+
+ /// <summary>Get a string representation of the version.</summary>
+ public override string ToString()
+ {
+ // version
+ string result = this.Patch != 0
+ ? $"{this.Major}.{this.Minor}.{this.Patch}"
+ : $"{this.Major}.{this.Minor}";
+
+ // tag
+ string tag = this.Tag;
+ if (tag != null)
+ result += $"-{tag}";
+ return result;
+ }
+
+ /// <summary>Parse a version string without throwing an exception if it fails.</summary>
+ /// <param name="version">The version string.</param>
+ /// <param name="parsed">The parsed representation.</param>
+ /// <returns>Returns whether parsing the version succeeded.</returns>
+ public static bool TryParse(string version, out ISemanticVersion parsed)
+ {
+ try
+ {
+ parsed = new SemanticVersion(version);
+ return true;
+ }
+ catch
+ {
+ parsed = null;
+ return false;
+ }
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get a normalised build tag.</summary>
+ /// <param name="tag">The tag to normalise.</param>
+ private string GetNormalisedTag(string tag)
+ {
+ tag = tag?.Trim();
+ return !string.IsNullOrWhiteSpace(tag) ? tag : null;
+ }
+
+ /// <summary>Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.</summary>
+ /// <param name="otherMajor">The major version to compare with this instance.</param>
+ /// <param name="otherMinor">The minor version to compare with this instance.</param>
+ /// <param name="otherPatch">The patch version to compare with this instance.</param>
+ /// <param name="otherTag">The prerelease tag to compare with this instance.</param>
+ private int CompareTo(int otherMajor, int otherMinor, int otherPatch, string otherTag)
+ {
+ const int same = 0;
+ const int curNewer = 1;
+ const int curOlder = -1;
+
+ // compare stable versions
+ if (this.Major != otherMajor)
+ return this.Major.CompareTo(otherMajor);
+ if (this.Minor != otherMinor)
+ return this.Minor.CompareTo(otherMinor);
+ if (this.Patch != otherPatch)
+ return this.Patch.CompareTo(otherPatch);
+ if (this.Tag == otherTag)
+ return same;
+
+ // stable supercedes pre-release
+ bool curIsStable = string.IsNullOrWhiteSpace(this.Tag);
+ bool otherIsStable = string.IsNullOrWhiteSpace(otherTag);
+ if (curIsStable)
+ return curNewer;
+ if (otherIsStable)
+ return curOlder;
+
+ // compare two pre-release tag values
+ string[] curParts = this.Tag.Split('.', '-');
+ string[] otherParts = otherTag.Split('.', '-');
+ for (int i = 0; i < curParts.Length; i++)
+ {
+ // longer prerelease tag supercedes if otherwise equal
+ if (otherParts.Length <= i)
+ return curNewer;
+
+ // compare if different
+ if (curParts[i] != otherParts[i])
+ {
+ // compare numerically if possible
+ {
+ if (int.TryParse(curParts[i], out int curNum) && int.TryParse(otherParts[i], out int otherNum))
+ return curNum.CompareTo(otherNum);
+ }
+
+ // else compare lexically
+ return string.Compare(curParts[i], otherParts[i], StringComparison.OrdinalIgnoreCase);
+ }
+ }
+
+ // fallback (this should never happen)
+ return string.Compare(this.ToString(), new SemanticVersion(otherMajor, otherMinor, otherPatch, otherTag).ToString(), StringComparison.InvariantCultureIgnoreCase);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI.Toolkit/StardewModdingAPI.Toolkit.csproj b/src/StardewModdingAPI.Toolkit/StardewModdingAPI.Toolkit.csproj
new file mode 100644
index 00000000..6688a2a1
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/StardewModdingAPI.Toolkit.csproj
@@ -0,0 +1,20 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFrameworks>net4.5;netstandard2.0</TargetFrameworks>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ </PropertyGroup>
+
+ <PropertyGroup>
+ <OutputPath>..\..\bin\$(Configuration)\SMAPI.Toolkit</OutputPath>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="HtmlAgilityPack" Version="1.7.2" />
+ <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
+ <PackageReference Include="Pathoschild.Http.FluentClient" Version="3.2.0" />
+ </ItemGroup>
+
+ <Import Project="..\..\build\common.targets" />
+
+</Project>
diff --git a/src/StardewModdingAPI.Toolkit/Utilities/PathUtilities.cs b/src/StardewModdingAPI.Toolkit/Utilities/PathUtilities.cs
new file mode 100644
index 00000000..2e74e7d9
--- /dev/null
+++ b/src/StardewModdingAPI.Toolkit/Utilities/PathUtilities.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Diagnostics.Contracts;
+using System.IO;
+using System.Linq;
+
+namespace StardewModdingAPI.Toolkit.Utilities
+{
+ /// <summary>Provides utilities for normalising file paths.</summary>
+ public static class PathUtilities
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The possible directory separator characters in a file path.</summary>
+ private static readonly char[] PossiblePathSeparators = new[] { '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }.Distinct().ToArray();
+
+ /// <summary>The preferred directory separator chaeacter in an asset key.</summary>
+ private static readonly string PreferredPathSeparator = Path.DirectorySeparatorChar.ToString();
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get the segments from a path (e.g. <c>/usr/bin/boop</c> => <c>usr</c>, <c>bin</c>, and <c>boop</c>).</summary>
+ /// <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>
+ public static string[] GetSegments(string path, int? limit = null)
+ {
+ return limit.HasValue
+ ? path.Split(PathUtilities.PossiblePathSeparators, limit.Value, StringSplitOptions.RemoveEmptyEntries)
+ : path.Split(PathUtilities.PossiblePathSeparators, StringSplitOptions.RemoveEmptyEntries);
+ }
+
+ /// <summary>Normalise path separators in a file path.</summary>
+ /// <param name="path">The file path to normalise.</param>
+ [Pure]
+ public static string NormalisePathSeparators(string path)
+ {
+ string[] parts = PathUtilities.GetSegments(path);
+ string normalised = string.Join(PathUtilities.PreferredPathSeparator, parts);
+ if (path.StartsWith(PathUtilities.PreferredPathSeparator))
+ normalised = PathUtilities.PreferredPathSeparator + normalised; // keep root slash
+ return normalised;
+ }
+
+ /// <summary>Get a directory or file path relative to a given source path.</summary>
+ /// <param name="sourceDir">The source folder path.</param>
+ /// <param name="targetPath">The target folder or file path.</param>
+ [Pure]
+ public static string GetRelativePath(string sourceDir, string targetPath)
+ {
+ // convert to URIs
+ Uri from = new Uri(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/");
+ Uri to = new Uri(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/");
+ if (from.Scheme != to.Scheme)
+ throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{sourceDir}'.");
+
+ // get relative path
+ string relative = PathUtilities.NormalisePathSeparators(Uri.UnescapeDataString(from.MakeRelativeUri(to).ToString()));
+ if (relative == "")
+ relative = "./";
+ return relative;
+ }
+ }
+}