godot/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs
Ignacio Etcheverry d569b447ff C#: Fix completion request with case insensitive resource path
Sometimes Visual Studio documents have the root path all in upper case.
Since Godot doesn't support loading resource files with a case insensitive path,
this makes script resource loading to fail when the Godot editor gets code
completion requests from Visual Studio.
This fix allows the resource path part of the path to be case insensitive. It
still doesn't support cases where the rest of the path is also case insensitive.
For that we would need a proper API for comparing paths. However, this fix
should be enough for our current cases.
2020-06-23 20:29:19 +02:00

69 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
namespace GodotTools.Core
{
public static class StringExtensions
{
public static string RelativeToPath(this string path, string dir)
{
// Make sure the directory ends with a path separator
dir = Path.Combine(dir, " ").TrimEnd();
if (Path.DirectorySeparatorChar == '\\')
dir = dir.Replace("/", "\\") + "\\";
Uri fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
Uri relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
return relRoot.MakeRelativeUri(fullPath).ToString();
}
public static string NormalizePath(this string path)
{
bool rooted = path.IsAbsolutePath();
path = path.Replace('\\', '/');
path = path[path.Length - 1] == '/' ? path.Substring(0, path.Length - 1) : path;
string[] parts = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
return rooted ? Path.DirectorySeparatorChar + path : path;
}
private static readonly string DriveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
public static bool IsAbsolutePath(this string path)
{
return path.StartsWith("/", StringComparison.Ordinal) ||
path.StartsWith("\\", StringComparison.Ordinal) ||
path.StartsWith(DriveRoot, StringComparison.Ordinal);
}
public static string ToSafeDirName(this string dirName, bool allowDirSeparator)
{
var invalidChars = new List<string> { ":", "*", "?", "\"", "<", ">", "|" };
if (allowDirSeparator)
{
// Directory separators are allowed, but disallow ".." to avoid going up the filesystem
invalidChars.Add("..");
}
else
{
invalidChars.Add("/");
}
string safeDirName = dirName.Replace("\\", "/").Trim();
foreach (string invalidChar in invalidChars)
safeDirName = safeDirName.Replace(invalidChar, "-");
return safeDirName;
}
}
}