Debian Codegraph @

modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs

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