-
Notifications
You must be signed in to change notification settings - Fork 79
SLVS-1883 Add RelativePathHelper for calculation of relative file paths to given root path #6046
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
georgii-borovinskikh-sonarsource
merged 2 commits into
feature/automatic-connected-mode
from
gb/relative-path-calculation
Feb 24, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
94 changes: 94 additions & 0 deletions
94
src/SLCore.UnitTests/Common/Helpers/RelativePathHelperTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
/* | ||
* SonarLint for Visual Studio | ||
* Copyright (C) 2016-2025 SonarSource SA | ||
* mailto:info AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
using System.IO; | ||
using SonarLint.VisualStudio.SLCore.Common.Helpers; | ||
|
||
namespace SonarLint.VisualStudio.SLCore.UnitTests.Common.Helpers; | ||
|
||
[TestClass] | ||
public class RelativePathHelperTests | ||
{ | ||
[DataRow("C:\\", "D:\\file.json", null)] | ||
[DataRow("C:\\", "C:\\file.json", "file.json")] | ||
[DataRow("C:\\one\\", "C:\\one\\file.json", "file.json")] | ||
[DataRow("C:\\one\\", "C:\\file.json", "..\\file.json")] | ||
[DataRow("C:\\one\\", "C:\\onetwo\\file.json", "..\\onetwo\\file.json")] | ||
[DataRow("C:\\one\\two\\", "C:\\one\\two\\file.json", "file.json")] | ||
[DataRow("C:\\one\\two\\", "C:\\one\\file.json", "..\\file.json")] | ||
[DataRow("C:\\one\\two\\", "C:\\one\\twothree\\file.json", "..\\twothree\\file.json")] | ||
[DataRow("C:\\one\\two\\", "C:\\twothree\\file.json", "..\\..\\twothree\\file.json")] | ||
[DataRow("C:\\one\\two\\", "C:\\oneone\\twothree\\file.json", "..\\..\\oneone\\twothree\\file.json")] | ||
[DataRow("C:\\one\\two\\three\\", "C:\\file.json", "..\\..\\..\\file.json")] | ||
[DataRow("C:\\one\\two\\", "D:\\one\\two\\file.json", null)] | ||
[DataRow("\\\\network\\one\\two\\three\\", "\\\\network\\file.json", "..\\..\\..\\file.json")] | ||
[DataTestMethod] | ||
public void GetRelativePathToRootFolder_ReturnsExpectedValues(string root, string file, string expected) => RelativePathHelper.GetRelativePathToRootFolder(root, file).Should().Be(expected); | ||
|
||
[TestMethod] | ||
public void GetRelativePathToRootFolder_RootPathNotEndsWithSeparator_Throws() | ||
{ | ||
const string root = "C:\\dirwithoutseparatorattheend"; | ||
var act = () => RelativePathHelper.GetRelativePathToRootFolder(root, "C:\\dirwithoutseparatorattheend\\file.json"); | ||
|
||
act.Should().Throw<ArgumentException>().WithMessage( | ||
$""" | ||
{string.Format(SLCoreStrings.RelativePathHelper_RootDoesNotEndWithSeparator, Path.DirectorySeparatorChar)} | ||
Parameter name: root | ||
""" | ||
); | ||
} | ||
|
||
[DataRow("path\\123")] | ||
[DataRow("\\path\\123")] | ||
[DataRow(".\\path\\123")] | ||
[DataRow("..\\path\\123")] | ||
[DataRow("notnetwork\\one\\two\\three\\")] | ||
[DataTestMethod] | ||
public void GetRelativePathToRootFolder_RootPathRelative_Throws(string path) | ||
{ | ||
var act = () => RelativePathHelper.GetRelativePathToRootFolder(path, "C:\\path\\123\\file.json"); | ||
|
||
act.Should().Throw<ArgumentException>().WithMessage( | ||
$""" | ||
{string.Format(SLCoreStrings.RelativePathHelper_NonAbsolutePath, path)} | ||
Parameter name: root | ||
""" | ||
); | ||
} | ||
|
||
[DataRow("path\\123\\file.json")] | ||
[DataRow("\\path\\123\\file.json")] | ||
[DataRow(".\\path\\123\\file.json")] | ||
[DataRow("..\\path\\123\\file.json")] | ||
[DataRow("notnetwork\\one\\two\\three.json")] | ||
[DataTestMethod] | ||
public void GetRelativePathToRootFolder_FilePathRelative_Throws(string path) | ||
{ | ||
var act = () => RelativePathHelper.GetRelativePathToRootFolder("C:\\path\\", path); | ||
|
||
act.Should().Throw<ArgumentException>().WithMessage( | ||
$""" | ||
{string.Format(SLCoreStrings.RelativePathHelper_NonAbsolutePath, path)} | ||
Parameter name: filePath | ||
""" | ||
); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
/* | ||
* SonarLint for Visual Studio | ||
* Copyright (C) 2016-2025 SonarSource SA | ||
* mailto:info AT sonarsource DOT com | ||
* | ||
* This program is free software; you can redistribute it and/or | ||
* modify it under the terms of the GNU Lesser General Public | ||
* License as published by the Free Software Foundation; either | ||
* version 3 of the License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | ||
* Lesser General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Lesser General Public License | ||
* along with this program; if not, write to the Free Software Foundation, | ||
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | ||
*/ | ||
|
||
using System.IO; | ||
using System.Text; | ||
|
||
namespace SonarLint.VisualStudio.SLCore.Common.Helpers; | ||
|
||
internal static class RelativePathHelper | ||
{ | ||
private static readonly char Separator = Path.DirectorySeparatorChar; | ||
|
||
public static string GetRelativePathToRootFolder(string root, string filePath) | ||
{ | ||
Validate(root, filePath); | ||
|
||
var commonParentPathLength = CalculateCommonPathLength(root, filePath); | ||
|
||
if (commonParentPathLength == 0) | ||
{ | ||
return null; | ||
} | ||
|
||
var depthOfRootRelativeToCommonParent = CalculateRemainingPathDepth(root, commonParentPathLength); | ||
var filePathRelativeToCommonParent = filePath.Substring(commonParentPathLength); | ||
|
||
return depthOfRootRelativeToCommonParent == 0 | ||
? filePathRelativeToCommonParent | ||
: MovePathUpwards(depthOfRootRelativeToCommonParent, filePathRelativeToCommonParent); | ||
} | ||
|
||
private static void Validate(string root, string filePath) | ||
{ | ||
if (!IsPathFullyQualified(root)) | ||
{ | ||
throw new ArgumentException(string.Format(SLCoreStrings.RelativePathHelper_NonAbsolutePath, root), nameof(root)); | ||
} | ||
|
||
if (!IsPathFullyQualified(filePath)) | ||
{ | ||
throw new ArgumentException(string.Format(SLCoreStrings.RelativePathHelper_NonAbsolutePath, filePath), nameof(filePath)); | ||
} | ||
|
||
if (root[root.Length - 1] != Separator) | ||
{ | ||
throw new ArgumentException(string.Format(SLCoreStrings.RelativePathHelper_RootDoesNotEndWithSeparator, Separator), nameof(root)); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Returns true if it is a fully qualified local or UNC path | ||
/// </summary> | ||
private static bool IsPathFullyQualified(string path) | ||
{ | ||
var root = Path.GetPathRoot(path); | ||
return root.StartsWith(@"\\") || root.EndsWith(@"\") && root != @"\"; | ||
} | ||
|
||
/// <summary> | ||
/// Constructs relative path by adding `..\` to filePathRelativeToCommonParent as many times, as it takes to get from root to common parent by doing `cd ..` | ||
/// </summary> | ||
private static string MovePathUpwards(int directoriesUp, string filePathRelativeToCommonParent) | ||
{ | ||
var sb = new StringBuilder(); | ||
|
||
for (var directoryNumber = 0; directoryNumber < directoriesUp; directoryNumber++) | ||
{ | ||
sb.Append(".."); | ||
sb.Append(Separator); | ||
} | ||
|
||
sb.Append(filePathRelativeToCommonParent); | ||
|
||
return sb.ToString(); | ||
} | ||
|
||
/// <summary> | ||
/// Calculates the depth of root path relative to common parent | ||
/// </summary> | ||
private static int CalculateRemainingPathDepth(string root, int commonPathLength) | ||
{ | ||
var depth = 0; | ||
for (var index = commonPathLength; index < root.Length; index++) | ||
{ | ||
if (root[index] == Separator) | ||
{ | ||
depth++; | ||
} | ||
} | ||
|
||
return depth; | ||
} | ||
|
||
/// <summary> | ||
/// Calculates the length of the common string prefix that ends on the directory separator, which is equivalent to the common parent path. | ||
/// If there is no common parent path, returns 0. | ||
/// </summary> | ||
private static int CalculateCommonPathLength(string path1, string path2) | ||
vnaskos-sonar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
int commonFilePathLenght; | ||
for (commonFilePathLenght = CalculateCommonPrefixLength(path1, path2); commonFilePathLenght > 0; commonFilePathLenght--) | ||
{ | ||
var index = commonFilePathLenght - 1; | ||
if (path1[index] == Separator) | ||
{ | ||
break; | ||
} | ||
} | ||
|
||
return commonFilePathLenght; | ||
} | ||
|
||
/// <summary> | ||
/// Calculates the length of the common string prefix. If there is no common prefix, returns 0. | ||
/// </summary> | ||
private static int CalculateCommonPrefixLength(string path1, string path2) | ||
{ | ||
int index; | ||
for (index = 0; index < path1.Length && index < path2.Length; index++) | ||
{ | ||
if (path1[index] != path2[index]) | ||
{ | ||
break; | ||
} | ||
} | ||
return index; | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.