StringExtensions.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. namespace GodotTools.Core
  6. {
  7. public static class StringExtensions
  8. {
  9. public static string RelativeToPath(this string path, string dir)
  10. {
  11. // Make sure the directory ends with a path separator
  12. dir = Path.Combine(dir, " ").TrimEnd();
  13. if (Path.DirectorySeparatorChar == '\\')
  14. dir = dir.Replace("/", "\\") + "\\";
  15. var fullPath = new Uri(Path.GetFullPath(path), UriKind.Absolute);
  16. var relRoot = new Uri(Path.GetFullPath(dir), UriKind.Absolute);
  17. // MakeRelativeUri converts spaces to %20, hence why we need UnescapeDataString
  18. return Uri.UnescapeDataString(relRoot.MakeRelativeUri(fullPath).ToString());
  19. }
  20. public static string NormalizePath(this string path)
  21. {
  22. if (string.IsNullOrEmpty(path))
  23. return path;
  24. bool rooted = path.IsAbsolutePath();
  25. path = path.Replace('\\', '/');
  26. path = path[path.Length - 1] == '/' ? path.Substring(0, path.Length - 1) : path;
  27. string[] parts = path.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
  28. path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim();
  29. if (!rooted)
  30. return path;
  31. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  32. {
  33. string maybeDrive = parts[0];
  34. if (maybeDrive.Length == 2 && maybeDrive[1] == ':')
  35. return path; // Already has drive letter
  36. }
  37. return Path.DirectorySeparatorChar + path;
  38. }
  39. private static readonly string DriveRoot = Path.GetPathRoot(Environment.CurrentDirectory);
  40. public static bool IsAbsolutePath(this string path)
  41. {
  42. return path.StartsWith("/", StringComparison.Ordinal) ||
  43. path.StartsWith("\\", StringComparison.Ordinal) ||
  44. path.StartsWith(DriveRoot, StringComparison.Ordinal);
  45. }
  46. public static string ToSafeDirName(this string dirName, bool allowDirSeparator = false)
  47. {
  48. var invalidChars = new List<string> {":", "*", "?", "\"", "<", ">", "|"};
  49. if (allowDirSeparator)
  50. {
  51. // Directory separators are allowed, but disallow ".." to avoid going up the filesystem
  52. invalidChars.Add("..");
  53. }
  54. else
  55. {
  56. invalidChars.Add("/");
  57. }
  58. string safeDirName = dirName.Replace("\\", "/").Trim();
  59. foreach (string invalidChar in invalidChars)
  60. safeDirName = safeDirName.Replace(invalidChar, "-");
  61. return safeDirName;
  62. }
  63. }
  64. }