From 4f3d7eaafc056a7a2b17b1657e069eb456f60f52 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 5 Sep 2020 15:00:38 -0400 Subject: make PathUtilities available to mods --- docs/release-notes.md | 1 + src/SMAPI/Utilities/PathUtilities.cs | 45 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/SMAPI/Utilities/PathUtilities.cs diff --git a/docs/release-notes.md b/docs/release-notes.md index e335990b..cdd141c3 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -22,6 +22,7 @@ * Internal changes to prepare for upcoming game updates. * For modders: + * Added `PathUtilities` to simplify working with file/asset names. * You can now read/write `SDate` values to JSON (e.g. for `config.json`, network mod messages, etc). * For the web UI: diff --git a/src/SMAPI/Utilities/PathUtilities.cs b/src/SMAPI/Utilities/PathUtilities.cs new file mode 100644 index 00000000..ea134468 --- /dev/null +++ b/src/SMAPI/Utilities/PathUtilities.cs @@ -0,0 +1,45 @@ +using System.Diagnostics.Contracts; +using ToolkitPathUtilities = StardewModdingAPI.Toolkit.Utilities.PathUtilities; + +namespace StardewModdingAPI.Utilities +{ + /// Provides utilities for normalizing file paths. + public static class PathUtilities + { + /********* + ** Public methods + *********/ + /// 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 ToolkitPathUtilities.GetSegments(path, limit); + } + + /// Normalize path separators in a file path. + /// The file path to normalize. + [Pure] + public static string NormalizePathSeparators(string path) + { + return ToolkitPathUtilities.NormalizePathSeparators(path); + } + + /// 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) + { + return ToolkitPathUtilities.IsSafeRelativePath(path); + } + + /// 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 ToolkitPathUtilities.IsSlug(str); + } + } +} -- cgit