Port TryMakeRelative and IsSubfolder

This commit is contained in:
YoshiRulz 2019-08-12 20:03:40 +10:00
parent b7249a99a5
commit 196594e1df
No known key found for this signature in database
GPG Key ID: C4DE31C245353FB7
1 changed files with 17 additions and 19 deletions

View File

@ -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
/// </summary>
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
/// <remarks>Algorithm for Windows taken from https://stackoverflow.com/a/7710620/7467292</remarks>
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"));
}
/// <summary>