From 196594e1df8dbf9a988600367e2401cbfaa3bdb4 Mon Sep 17 00:00:00 2001 From: YoshiRulz Date: Mon, 12 Aug 2019 20:03:40 +1000 Subject: [PATCH] Port TryMakeRelative and IsSubfolder --- BizHawk.Client.Common/PathManager.cs | 36 +++++++++++++--------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/BizHawk.Client.Common/PathManager.cs b/BizHawk.Client.Common/PathManager.cs index 14af64ccbb..66ba78f4d2 100644 --- a/BizHawk.Client.Common/PathManager.cs +++ b/BizHawk.Client.Common/PathManager.cs @@ -3,6 +3,7 @@ using System.Linq; using System.IO; using System.Reflection; +using BizHawk.Common; using BizHawk.Common.StringExtensions; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; @@ -403,16 +404,14 @@ namespace BizHawk.Client.Common /// public static string TryMakeRelative(string absolutePath, string system = null) { - var parentPath = string.IsNullOrWhiteSpace(system) ? - GetGlobalBasePathAbsolute() : - MakeAbsolutePath(GetPlatformBase(system), system); + var parentPath = string.IsNullOrWhiteSpace(system) + ? GetGlobalBasePathAbsolute() + : MakeAbsolutePath(GetPlatformBase(system), system); + if (!IsSubfolder(parentPath, absolutePath)) return absolutePath; - if (IsSubfolder(parentPath, absolutePath)) - { - return absolutePath.Replace(parentPath, "."); - } - - return absolutePath; + return OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows + ? absolutePath.Replace(parentPath, ".") + : "./" + OSTailoredCode.SimpleSubshell("realpath", $"--relative-to=\"{parentPath}\" \"{absolutePath}\"", $"invalid path {absolutePath} or missing realpath binary"); } public static string MakeRelativeTo(string absolutePath, string basePath) @@ -425,24 +424,23 @@ namespace BizHawk.Client.Common return absolutePath; } - // http://stackoverflow.com/questions/3525775/how-to-check-if-directory-1-is-a-subdirectory-of-dir2-and-vice-versa + /// Algorithm for Windows taken from https://stackoverflow.com/a/7710620/7467292 private static bool IsSubfolder(string parentPath, string childPath) { - var parentUri = new Uri(parentPath); - - var childUri = new DirectoryInfo(childPath).Parent; - - while (childUri != null) + if (OSTailoredCode.CurrentOS == OSTailoredCode.DistinctOS.Windows) { - if (new Uri(childUri.FullName) == parentUri) + var parentUri = new Uri(parentPath); + + for (var childUri = new DirectoryInfo(childPath); childUri != null; childUri = childUri?.Parent) { - return true; + if (new Uri(childUri.FullName) == parentUri) return true; } - childUri = childUri.Parent; + return false; } - return false; + return OSTailoredCode.SimpleSubshell("realpath", $"-L \"{childPath}\"", $"invalid path {childPath} or missing realpath binary") + .StartsWith(OSTailoredCode.SimpleSubshell("realpath", $"-L \"{parentPath}\"", $"invalid path {parentPath} or missing realpath binary")); } ///