Skip to content

Commit 8915842

Browse files
authored
GetRelative paths accepts paths shorter than the base directory (#72166)
1 parent d24b5bb commit 8915842

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/Compilers/Core/Portable/FileSystem/PathUtilities.cs

+4-1
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,8 @@ public static string GetRelativePath(string directory, string fullPath)
562562
int index = 0;
563563

564564
// find index where full path diverges from base path
565-
for (; index < directoryPathParts.Length; index++)
565+
var maxSearchIndex = Math.Min(directoryPathParts.Length, fullPathParts.Length);
566+
for (; index < maxSearchIndex; index++)
566567
{
567568
if (!PathsEqual(directoryPathParts[index], fullPathParts[index]))
568569
{
@@ -593,6 +594,8 @@ public static string GetRelativePath(string directory, string fullPath)
593594
relativePath = CombinePathsUnchecked(relativePath, fullPathParts[i]);
594595
}
595596

597+
relativePath = TrimTrailingSeparators(relativePath);
598+
596599
return relativePath;
597600
}
598601

src/Workspaces/CoreTest/UtilityTest/FilePathUtilitiesTests.cs

+22
Original file line numberDiff line numberDiff line change
@@ -99,5 +99,27 @@ public void GetRelativePath_WithBaseDirectoryMatchingIncompletePortionOfFullPath
9999

100100
Assert.Equal(expected: @"..\Beta2\Gamma", actual: result);
101101
}
102+
103+
[ConditionalTheory(typeof(WindowsOnly)), WorkItem(72043, "https://github.com/dotnet/roslyn/issues/72043")]
104+
[InlineData(@"C:\Alpha", @"C:\", @"..")]
105+
[InlineData(@"C:\Alpha\Beta", @"C:\", @"..\..")]
106+
[InlineData(@"C:\Alpha\Beta", @"C:\Gamma", @"..\..\Gamma")]
107+
public void GetRelativePath_WithFullPathShorterThanBasePath_Windows(string baseDirectory, string fullPath, string expected)
108+
{
109+
var result = PathUtilities.GetRelativePath(baseDirectory, fullPath);
110+
111+
Assert.Equal(expected, result);
112+
}
113+
114+
[ConditionalTheory(typeof(UnixLikeOnly)), WorkItem(72043, "https://github.com/dotnet/roslyn/issues/72043")]
115+
[InlineData("/Alpha", "/", "..")]
116+
[InlineData("/Alpha/Beta", "/", "../..")]
117+
[InlineData("/Alpha/Beta", "/Gamma", "../../Gamma")]
118+
public void GetRelativePath_WithFullPathShorterThanBasePath_Unix(string baseDirectory, string fullPath, string expected)
119+
{
120+
var result = PathUtilities.GetRelativePath(baseDirectory, fullPath);
121+
122+
Assert.Equal(expected, result);
123+
}
102124
}
103125
}

0 commit comments

Comments
 (0)