Skip to content
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

SLVS-1883 Add RelativePathHelper for calculation of relative file paths to given root path #6046

Open
wants to merge 2 commits into
base: feature/automatic-connected-mode
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions src/SLCore.UnitTests/Common/Helpers/RelativePathHelperTests.cs
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
"""
);
}
}
145 changes: 145 additions & 0 deletions src/SLCore/Common/Helpers/RelativePathHelper.cs
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)
{
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;
}
}
19 changes: 18 additions & 1 deletion src/SLCore/SLCoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/SLCore/SLCoreStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,10 @@
<data name="ServerCertificateInfobar_ShowLogs" xml:space="preserve">
<value>Show logs</value>
</data>
<data name="RelativePathHelper_NonAbsolutePath" xml:space="preserve">
<value>Path must be fully-qualified. ({0})</value>
</data>
<data name="RelativePathHelper_RootDoesNotEndWithSeparator" xml:space="preserve">
<value>Root path must end with a {0} separator</value>
</data>
</root>