Skip to content

Commit

Permalink
Update NormalizePath to be more robust (#1152)
Browse files Browse the repository at this point in the history
  • Loading branch information
cobya authored Jun 4, 2024
1 parent b3e3c9d commit 9f1e5a9
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
14 changes: 12 additions & 2 deletions src/Microsoft.ComponentDetection.Common/PathUtilityService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ public string ResolvePhysicalPath(string path)

private string ResolvePathFromInfo(FileSystemInfo info) => info.LinkTarget ?? info.FullName;

public string NormalizePath(string path) =>
path?.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
public string NormalizePath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return path;
}

// Normalize the path directory seperator to / on Unix systems and on Windows.
// This is the behavior we want as Windows accepts / as a separator.
// AltDirectorySeparatorChar is / on Unix and on Windows.
return path.Replace('\\', Path.AltDirectorySeparatorChar);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public interface IPathUtilityService
bool MatchesPattern(string searchPattern, string fileName);

/// <summary>
/// Normalizes the path to the system based separator.
/// Normalize the path directory seperator to / on Unix systems and on Windows.
/// This is the behavior we want as Windows accepts / as a separator.
/// </summary>
/// <param name="path">the path.</param>
/// <returns>normalized path.</returns>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
namespace Microsoft.ComponentDetection.Common.Tests;

using System.IO;
using FluentAssertions;
using Microsoft.ComponentDetection.Common;
using Microsoft.Extensions.Logging.Abstractions;
Expand All @@ -16,14 +15,20 @@ public void PathShouldBeNormalized()
{
var service = new PathUtilityService(new NullLogger<PathUtilityService>());
var path = "Users\\SomeUser\\someDir\\someFile";
var expectedPath = "Users/SomeUser/someDir/someFile";
var normalizedPath = service.NormalizePath(path);
if (Path.DirectorySeparatorChar == '\\')
{
normalizedPath.Should().Be(path);
}
else
{
normalizedPath.Should().Be(string.Join(Path.DirectorySeparatorChar, path.Split('\\')));
}

normalizedPath.Should().Be(expectedPath);
}

[TestMethod]
public void AbsolutePathShouldBeNormalized()
{
var service = new PathUtilityService(new NullLogger<PathUtilityService>());
var path = "C:\\Users\\SomeUser\\someDir\\someFile";
var expectedPath = "C:/Users/SomeUser/someDir/someFile";
var normalizedPath = service.NormalizePath(path);

normalizedPath.Should().Be(expectedPath);
}
}

0 comments on commit 9f1e5a9

Please sign in to comment.