18 Commits
1.3.0 ... 1.3.3

Author SHA1 Message Date
Matt Nadareski
8e3293dd7d Bump version 2024-04-02 15:57:38 -04:00
Matt Nadareski
7ac4df8201 Add quoted string reading 2024-04-02 15:52:15 -04:00
Matt Nadareski
f888cd4e57 Bump version 2024-03-12 16:27:56 -04:00
Matt Nadareski
04fc2dc96e Fix incorrect nullability check 2024-03-11 13:38:10 -04:00
Matt Nadareski
2371813175 Allow Ensure to take a null string 2024-03-11 13:35:34 -04:00
Matt Nadareski
99b3bb25f2 Make ParentablePath normalization clearer 2024-03-05 11:34:38 -05:00
Matt Nadareski
2ee40e341f Ensure paths are normalized on ParentablePath creation 2024-03-05 11:02:46 -05:00
Matt Nadareski
90ed6a9a65 Normalize paths to Windows for tests 2024-03-05 10:54:58 -05:00
Matt Nadareski
89e29c9cab Port tests from SabreTools 2024-03-05 10:45:31 -05:00
Matt Nadareski
1a6ff6d64f Move library to subfolder to prep for test additions 2024-03-05 10:40:45 -05:00
Matt Nadareski
878e9e97db Bump version 2024-03-05 10:17:31 -05:00
Matt Nadareski
09acfd3ad2 Parentable path output directory ensure 2024-03-05 10:15:16 -05:00
Matt Nadareski
8c2eff6e3e Trim ParentablePath pieces 2024-03-05 09:51:00 -05:00
Matt Nadareski
dbf8548d8c Use Matching to replace NaturalSort 2024-02-29 21:06:56 -05:00
Matt Nadareski
bcbf5bff42 Add notes about NaturalSort namespace 2024-02-29 00:25:02 -05:00
Matt Nadareski
c3c58f004a Update copyright date 2024-02-27 19:12:28 -05:00
Matt Nadareski
cf11fe50d0 Add nuget package and PR workflows 2024-02-27 19:12:17 -05:00
Matt Nadareski
5ddd1e4213 Use more lenient file reading 2023-12-13 15:44:16 -05:00
25 changed files with 286 additions and 302 deletions

49
.github/workflows/build_nupkg.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Nuget Pack
on:
push:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build library
run: dotnet build
- name: Run tests
run: dotnet test
- name: Pack
run: dotnet pack
- name: Upload build
uses: actions/upload-artifact@v4
with:
name: 'Nuget Package'
path: 'SabreTools.IO/bin/Release/*.nupkg'
- name: Upload to rolling
uses: ncipollo/release-action@v1.14.0
with:
allowUpdates: True
artifacts: 'SabreTools.IO/bin/Release/*.nupkg'
body: 'Last built commit: ${{ github.sha }}'
name: 'Rolling Release'
prerelease: True
replacesArtifacts: True
tag: "rolling"
updateOnlyUnreleased: True

20
.github/workflows/check_pr.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Build PR
on: [pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Build
run: dotnet build
- name: Run tests
run: dotnet test

View File

@@ -1,104 +0,0 @@
/*
*
* Links for info and original source code:
*
* https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
* http://www.codeproject.com/Articles/22517/Natural-Sort-Comparer
*
* Exact code implementation used with permission, originally by motoschifo
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
/// TODO: Make this namespace a separate library
namespace NaturalSort
{
internal class NaturalComparer : Comparer<string>, IDisposable
{
private readonly Dictionary<string, string[]> table;
public NaturalComparer()
{
table = [];
}
public void Dispose()
{
table.Clear();
}
public override int Compare(string? x, string? y)
{
if (x == null || y == null)
{
if (x == null && y != null)
return -1;
else if (x != null && y == null)
return 1;
else
return 0;
}
if (x.ToLowerInvariant() == y.ToLowerInvariant())
{
return x.CompareTo(y);
}
if (!table.TryGetValue(x, out string[]? x1))
{
//x1 = Regex.Split(x.Replace(" ", string.Empty), "([0-9]+)");
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(x, x1);
}
if (!table.TryGetValue(y, out string[]? y1))
{
//y1 = Regex.Split(y.Replace(" ", string.Empty), "([0-9]+)");
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(y, y1);
}
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
return PartCompare(x1[i], y1[i]);
}
}
if (y1.Length > x1.Length)
{
return 1;
}
else if (x1.Length > y1.Length)
{
return -1;
}
else
{
return x.CompareTo(y);
}
}
private static int PartCompare(string left, string right)
{
if (!long.TryParse(left, out long x))
{
return NaturalComparerUtil.CompareNumeric(left, right);
}
if (!long.TryParse(right, out long y))
{
return NaturalComparerUtil.CompareNumeric(left, right);
}
// If we have an equal part, then make sure that "longer" ones are taken into account
if (x.CompareTo(y) == 0)
{
return left.Length - right.Length;
}
return x.CompareTo(y);
}
}
}

View File

@@ -1,79 +0,0 @@
using System.IO;
/// TODO: Make this namespace a separate library
namespace NaturalSort
{
internal static class NaturalComparerUtil
{
public static int CompareNumeric(string s1, string s2)
{
// Save the orginal strings, for later comparison
string s1orig = s1;
string s2orig = s2;
// We want to normalize the strings, so we set both to lower case
s1 = s1.ToLowerInvariant();
s2 = s2.ToLowerInvariant();
// If the strings are the same exactly, return
if (s1 == s2)
return s1orig.CompareTo(s2orig);
// If one is null, then say that's less than
if (s1 == null)
return -1;
if (s2 == null)
return 1;
// Now split into path parts after converting AltDirSeparator to DirSeparator
s1 = s1.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
s2 = s2.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string[] s1parts = s1.Split(Path.DirectorySeparatorChar);
string[] s2parts = s2.Split(Path.DirectorySeparatorChar);
// Then compare each part in turn
for (int j = 0; j < s1parts.Length && j < s2parts.Length; j++)
{
int compared = CompareNumericPart(s1parts[j], s2parts[j]);
if (compared != 0)
return compared;
}
// If we got out here, then it looped through at least one of the strings
if (s1parts.Length > s2parts.Length)
return 1;
if (s1parts.Length < s2parts.Length)
return -1;
return s1orig.CompareTo(s2orig);
}
private static int CompareNumericPart(string s1, string s2)
{
// Otherwise, loop through until we have an answer
for (int i = 0; i < s1.Length && i < s2.Length; i++)
{
int s1c = s1[i];
int s2c = s2[i];
// If the characters are the same, continue
if (s1c == s2c)
continue;
// If they're different, check which one was larger
if (s1c > s2c)
return 1;
if (s1c < s2c)
return -1;
}
// If we got out here, then it looped through at least one of the strings
if (s1.Length > s2.Length)
return 1;
if (s1.Length < s2.Length)
return -1;
return 0;
}
}
}

View File

@@ -1,104 +0,0 @@
/*
*
* Links for info and original source code:
*
* https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
* http://www.codeproject.com/Articles/22517/Natural-Sort-Comparer
*
* Exact code implementation used with permission, originally by motoschifo
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
/// TODO: Make this namespace a separate library
namespace NaturalSort
{
internal class NaturalReversedComparer : Comparer<string>, IDisposable
{
private readonly Dictionary<string, string[]> table;
public NaturalReversedComparer()
{
table = [];
}
public void Dispose()
{
table.Clear();
}
public override int Compare(string? x, string? y)
{
if (x == null || y == null)
{
if (x == null && y != null)
return -1;
else if (x != null && y == null)
return 1;
else
return 0;
}
if (y.ToLowerInvariant() == x.ToLowerInvariant())
{
return y.CompareTo(x);
}
if (!table.TryGetValue(x, out string[]? x1))
{
//x1 = Regex.Split(x.Replace(" ", string.Empty), "([0-9]+)");
x1 = Regex.Split(x.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(x, x1);
}
if (!table.TryGetValue(y, out string[]? y1))
{
//y1 = Regex.Split(y.Replace(" ", string.Empty), "([0-9]+)");
y1 = Regex.Split(y.ToLowerInvariant(), "([0-9]+)").Where(s => !string.IsNullOrEmpty(s)).ToArray();
table.Add(y, y1);
}
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
return PartCompare(x1[i], y1[i]);
}
}
if (y1.Length > x1.Length)
{
return 1;
}
else if (x1.Length > y1.Length)
{
return -1;
}
else
{
return y.CompareTo(x);
}
}
private static int PartCompare(string left, string right)
{
if (!long.TryParse(left, out long x))
{
return NaturalComparerUtil.CompareNumeric(right, left);
}
if (!long.TryParse(right, out long y))
{
return NaturalComparerUtil.CompareNumeric(right, left);
}
// If we have an equal part, then make sure that "longer" ones are taken into account
if (y.CompareTo(x) == 0)
{
return right.Length - left.Length;
}
return y.CompareTo(x);
}
}
}

View File

@@ -0,0 +1,23 @@
using Xunit;
namespace SabreTools.IO.Test
{
public class IOExtensionsTests
{
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData(" ", null)]
[InlineData("no-extension", null)]
[InlineData("NO-EXTENSION", null)]
[InlineData("no-extension.", null)]
[InlineData("NO-EXTENSION.", null)]
[InlineData("filename.ext", "ext")]
[InlineData("FILENAME.EXT", "ext")]
public void NormalizedExtensionTest(string? path, string? expected)
{
string? actual = path.GetNormalizedExtension();
Assert.Equal(expected, actual);
}
}
}

View File

@@ -0,0 +1,70 @@
using System;
using Xunit;
namespace SabreTools.IO.Test
{
public class ParentablePathTests
{
[Theory]
[InlineData("", null, false, null)]
[InlineData("", null, true, null)]
[InlineData(" ", null, false, null)]
[InlineData(" ", null, true, null)]
[InlineData("C:\\Directory\\Filename.ext", null, false, "Filename.ext")]
[InlineData("C:\\Directory\\Filename.ext", null, true, "Filename.ext")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", false, "Filename.ext")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", true, "Filename.ext")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", false, "SubDir\\Filename.ext")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", true, "SubDir-Filename.ext")]
public void NormalizedFileNameTest(string current, string? parent, bool sanitize, string? expected)
{
var path = new ParentablePath(current, parent);
string? actual = path.GetNormalizedFileName(sanitize);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("", null, null, false, null)]
[InlineData("", null, null, true, null)]
[InlineData(" ", null, null, false, null)]
[InlineData(" ", null, null, true, null)]
[InlineData("C:\\Directory\\Filename.ext", null, null, false, null)]
[InlineData("C:\\Directory\\Filename.ext", null, null, true, "C:\\Directory")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", null, false, null)]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", null, true, "C:\\Directory")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", null, false, null)]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", null, true, "C:\\Directory\\SubDir")]
[InlineData("", null, "D:\\OutputDirectory", false, null)]
[InlineData("", null, "D:\\OutputDirectory", true, null)]
[InlineData(" ", null, "D:\\OutputDirectory", false, null)]
[InlineData(" ", null, "D:\\OutputDirectory", true, null)]
[InlineData("C:\\Directory\\Filename.ext", null, "D:\\OutputDirectory", false, "D:\\OutputDirectory")]
[InlineData("C:\\Directory\\Filename.ext", null, "D:\\OutputDirectory", true, "C:\\Directory")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", "D:\\OutputDirectory", false, "D:\\OutputDirectory")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", "D:\\OutputDirectory", true, "C:\\Directory")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", "D:\\OutputDirectory", false, "D:\\OutputDirectory\\SubDir")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", "D:\\OutputDirectory", true, "C:\\Directory\\SubDir")]
[InlineData("", null, "%cd%", false, null)]
[InlineData("", null, "%cd%", true, null)]
[InlineData(" ", null, "%cd%", false, null)]
[InlineData(" ", null, "%cd%", true, null)]
[InlineData("C:\\Directory\\Filename.ext", null, "%cd%", false, "%cd%")]
[InlineData("C:\\Directory\\Filename.ext", null, "%cd%", true, "C:\\Directory")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", "%cd%", false, "%cd%")]
[InlineData("C:\\Directory\\Filename.ext", "C:\\Directory\\Filename.ext", "%cd%", true, "C:\\Directory")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", "%cd%", false, "%cd%\\Directory\\SubDir")]
[InlineData("C:\\Directory\\SubDir\\Filename.ext", "C:\\Directory", "%cd%", true, "C:\\Directory\\SubDir")]
public void GetOutputPathTest(string current, string? parent, string? outDir, bool inplace, string? expected)
{
// Hacks because I can't use environment vars as parameters
if (outDir == "%cd%")
outDir = Environment.CurrentDirectory.TrimEnd('\\', '/');
if (expected?.Contains("%cd%") == true)
expected = expected.Replace("%cd%", Environment.CurrentDirectory.TrimEnd('\\', '/'));
var path = new ParentablePath(current, parent);
string? actual = path.GetOutputPath(outDir, inplace);
Assert.Equal(expected, actual);
}
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net6.0;net8.0</TargetFrameworks>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SabreTools.IO\SabreTools.IO.csproj" />
</ItemGroup>
</Project>

View File

@@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SabreTools.IO", "SabreTools.IO.csproj", "{87CE4411-80D9-49FF-894C-761F1C20D9A5}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SabreTools.IO", "SabreTools.IO\SabreTools.IO.csproj", "{87CE4411-80D9-49FF-894C-761F1C20D9A5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SabreTools.IO.Test", "SabreTools.IO.Test\SabreTools.IO.Test.csproj", "{A9767735-5042-48A1-849C-96035DB1DD53}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -18,5 +20,9 @@ Global
{87CE4411-80D9-49FF-894C-761F1C20D9A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{87CE4411-80D9-49FF-894C-761F1C20D9A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{87CE4411-80D9-49FF-894C-761F1C20D9A5}.Release|Any CPU.Build.0 = Release|Any CPU
{A9767735-5042-48A1-849C-96035DB1DD53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9767735-5042-48A1-849C-96035DB1DD53}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9767735-5042-48A1-849C-96035DB1DD53}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9767735-5042-48A1-849C-96035DB1DD53}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -16,14 +16,14 @@ namespace SabreTools.IO
/// <param name="dir">Directory to check</param>
/// <param name="create">True if the directory should be created, false otherwise (default)</param>
/// <returns>Full path to the directory</returns>
public static string Ensure(this string dir, bool create = false)
public static string Ensure(this string? dir, bool create = false)
{
// If the output directory is invalid
if (string.IsNullOrEmpty(dir))
dir = PathTool.GetRuntimeDirectory();
// Get the full path for the output directory
dir = Path.GetFullPath(dir.Trim('"'));
dir = Path.GetFullPath(dir!.Trim('"'));
// If we're creating the output folder, do so
if (create && !Directory.Exists(dir))
@@ -50,7 +50,7 @@ namespace SabreTools.IO
// Try to open the file
try
{
FileStream file = File.OpenRead(filename);
FileStream file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (file == null)
return Encoding.Default;

View File

@@ -89,7 +89,7 @@ namespace SabreTools.IO
if (!File.Exists(path))
return false;
using var fileStream = File.OpenRead(path);
using var fileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return Parse(fileStream);
}

View File

@@ -20,8 +20,8 @@ namespace SabreTools.IO
public ParentablePath(string currentPath, string? parentPath = null)
{
CurrentPath = currentPath;
ParentPath = parentPath;
CurrentPath = currentPath.Trim();
ParentPath = parentPath?.Trim();
}
/// <summary>
@@ -39,7 +39,7 @@ namespace SabreTools.IO
string filename = Path.GetFileName(CurrentPath);
// If we have a true ParentPath, remove it from CurrentPath and return the remainder
if (string.IsNullOrEmpty(ParentPath) && !string.Equals(CurrentPath, ParentPath, StringComparison.Ordinal))
if (!string.IsNullOrEmpty(ParentPath) && !PathsEqual(CurrentPath, ParentPath))
filename = CurrentPath.Remove(0, ParentPath!.Length + 1);
// If we're sanitizing the path after, do so
@@ -55,13 +55,14 @@ namespace SabreTools.IO
/// <param name="outDir">Output directory to use</param>
/// <param name="inplace">True if the output file should go to the same input folder, false otherwise</param>
/// <returns>Complete output path</returns>
public string? GetOutputPath(string outDir, bool inplace)
public string? GetOutputPath(string? outDir, bool inplace)
{
// If the current path is empty, we can't do anything
if (string.IsNullOrEmpty(CurrentPath))
return null;
// If the output dir is empty (and we're not inplace), we can't do anything
outDir = outDir?.Trim();
if (string.IsNullOrEmpty(outDir) && !inplace)
return null;
@@ -89,7 +90,41 @@ namespace SabreTools.IO
|| workingParent.EndsWith(Path.DirectorySeparatorChar.ToString())
|| workingParent.EndsWith(Path.AltDirectorySeparatorChar.ToString()) ? 0 : 1;
return Path.GetDirectoryName(Path.Combine(outDir, CurrentPath.Remove(0, workingParent.Length + extraLength)));
return Path.GetDirectoryName(Path.Combine(outDir!, CurrentPath.Remove(0, workingParent.Length + extraLength)));
}
/// <summary>
/// Determine if two paths are equal or not
/// </summary>
private static bool PathsEqual(string? path1, string? path2, bool caseSenstive = false)
{
// Handle null path cases
if (path1 == null && path2 == null)
return true;
else if (path1 == null ^ path2 == null)
return false;
// Normalize the paths before comparing
path1 = NormalizeDirectorySeparators(path1);
path2 = NormalizeDirectorySeparators(path2);
// Compare and return
return string.Equals(path1, path2, caseSenstive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Normalize directory separators for the current system
/// </summary>
/// <param name="input">Input path that may contain separators</param>
/// <returns>Normalized path with separators fixed, if possible</returns>
private static string? NormalizeDirectorySeparators(string? input)
{
// Null inputs are skipped
if (input == null)
return null;
// Replace alternate directory separators with the correct one
return input.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
}
}

View File

@@ -1,7 +1,6 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NaturalSort;
using SabreTools.Matching;
namespace SabreTools.IO
{

View File

@@ -7,12 +7,12 @@
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>1.3.0</Version>
<Version>1.3.3</Version>
<!-- Package Properties -->
<Authors>Matt Nadareski</Authors>
<Description>Common IO utilities by other SabreTools projects</Description>
<Copyright>Copyright (c) Matt Nadareski 2019-2023</Copyright>
<Copyright>Copyright (c) Matt Nadareski 2019-2024</Copyright>
<PackageProjectUrl>https://github.com/SabreTools/</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/SabreTools/SabreTools.IO</RepositoryUrl>
@@ -22,7 +22,7 @@
</PropertyGroup>
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath=""/>
<None Include="../README.md" Pack="true" PackagePath=""/>
</ItemGroup>
<!-- Support for old .NET versions -->
@@ -30,4 +30,8 @@
<PackageReference Include="Net30.LinqBridge" Version="1.3.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SabreTools.Matching" Version="1.3.1" />
</ItemGroup>
</Project>

View File

@@ -230,6 +230,44 @@ namespace SabreTools.IO
return encoding.GetString([.. tempBuffer]);
}
/// <summary>
/// Read a string that is terminated by a newline but contains a quoted portion that
/// may also contain a newline from the stream
/// </summary>
public static string? ReadQuotedString(this Stream stream) => stream.ReadQuotedString(Encoding.Default);
/// <summary>
/// Read a string that is terminated by a newline but contains a quoted portion that
/// may also contain a newline from the stream
/// </summary>
public static string? ReadQuotedString(this Stream stream, Encoding encoding)
{
if (stream.Position >= stream.Length)
return null;
var bytes = new List<byte>();
bool openQuote = false;
while (stream.Position < stream.Length)
{
// Read the byte value
byte b = stream.ReadByteValue();
// If we have a quote, flip the flag
if (b == (byte)'"')
openQuote = !openQuote;
// If we have a newline not in a quoted string, exit the loop
else if (b == (byte)'\n' && !openQuote)
break;
// Add the byte to the set
bytes.Add(b);
}
var line = encoding.GetString([.. bytes]);
return line.TrimEnd();
}
/// <summary>
/// Seek to a specific point in the stream, if possible
/// </summary>