Skip to content

Commit

Permalink
GetRelative paths accepts paths shorter than the base directory (#72166)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnakinRaW authored Mar 6, 2024
1 parent d24b5bb commit 8915842
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Compilers/Core/Portable/FileSystem/PathUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,8 @@ public static string GetRelativePath(string directory, string fullPath)
int index = 0;

// find index where full path diverges from base path
for (; index < directoryPathParts.Length; index++)
var maxSearchIndex = Math.Min(directoryPathParts.Length, fullPathParts.Length);
for (; index < maxSearchIndex; index++)
{
if (!PathsEqual(directoryPathParts[index], fullPathParts[index]))
{
Expand Down Expand Up @@ -593,6 +594,8 @@ public static string GetRelativePath(string directory, string fullPath)
relativePath = CombinePathsUnchecked(relativePath, fullPathParts[i]);
}

relativePath = TrimTrailingSeparators(relativePath);

return relativePath;
}

Expand Down
22 changes: 22 additions & 0 deletions src/Workspaces/CoreTest/UtilityTest/FilePathUtilitiesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,27 @@ public void GetRelativePath_WithBaseDirectoryMatchingIncompletePortionOfFullPath

Assert.Equal(expected: @"..\Beta2\Gamma", actual: result);
}

[ConditionalTheory(typeof(WindowsOnly)), WorkItem(72043, "https://github.com/dotnet/roslyn/issues/72043")]
[InlineData(@"C:\Alpha", @"C:\", @"..")]
[InlineData(@"C:\Alpha\Beta", @"C:\", @"..\..")]
[InlineData(@"C:\Alpha\Beta", @"C:\Gamma", @"..\..\Gamma")]
public void GetRelativePath_WithFullPathShorterThanBasePath_Windows(string baseDirectory, string fullPath, string expected)
{
var result = PathUtilities.GetRelativePath(baseDirectory, fullPath);

Assert.Equal(expected, result);
}

[ConditionalTheory(typeof(UnixLikeOnly)), WorkItem(72043, "https://github.com/dotnet/roslyn/issues/72043")]
[InlineData("/Alpha", "/", "..")]
[InlineData("/Alpha/Beta", "/", "../..")]
[InlineData("/Alpha/Beta", "/Gamma", "../../Gamma")]
public void GetRelativePath_WithFullPathShorterThanBasePath_Unix(string baseDirectory, string fullPath, string expected)
{
var result = PathUtilities.GetRelativePath(baseDirectory, fullPath);

Assert.Equal(expected, result);
}
}
}

0 comments on commit 8915842

Please sign in to comment.