Skip to content

Commit

Permalink
Add file path validation
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt committed Jan 22, 2025
1 parent f74cf8f commit abb9496
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Tests/Testing.Common/Testing/AdditionalFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ public AdditionalFile(string source, string? expectedSource = null, string? path
{
Source = source ?? throw new ArgumentNullException(nameof(source));
ExpectedSource = expectedSource;

FilePathVerifier.VerifyFilePath(path);
Path = path;
}

Expand Down
39 changes: 39 additions & 0 deletions src/Tests/Testing.Common/Testing/FilePathVerifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.IO;
using System.Linq;

namespace Roslynator.Testing;

internal static class FilePathVerifier
{
private static readonly char[] _invalidPathChars = Path.GetInvalidPathChars();
private static readonly char[] _invalidFileNameChars = Path.GetInvalidFileNameChars();

public static void VerifyFilePath(string? path)
{
if (path is null)
return;

if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException("File path cannot be empty or contain only whitespace", nameof(path));

if (path.IndexOfAny(_invalidPathChars) >= 0)
throw new ArgumentException("File path contains invalid character(s)", nameof(path));

if (path[path.Length - 1] == Path.DirectorySeparatorChar
|| path[path.Length - 1] == Path.AltDirectorySeparatorChar)
{
throw new ArgumentException("File path cannot end with directory separator", nameof(path));
}

var dirSeparatorIndex = FileSystemHelpers.LastIndexOfDirectorySeparator(path);
if (dirSeparatorIndex >= 0)
{
for (int i = dirSeparatorIndex + 1; i < path.Length; i++)
{
if (_invalidFileNameChars.Contains(path[i]))
throw new ArgumentException("File name contains invalid character(s)", nameof(path));
}
}
}
}
2 changes: 2 additions & 0 deletions src/Tests/Testing.Common/Testing/TestFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ public TestFile(string source, string? expectedSource = null, string? path = nul
{
Source = source;
ExpectedSource = expectedSource;

FilePathVerifier.VerifyFilePath(path);
Path = path;
}

Expand Down

0 comments on commit abb9496

Please sign in to comment.