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

Metadata XML enumerators #89

Merged
merged 8 commits into from
Dec 21, 2024
Merged
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
16 changes: 7 additions & 9 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
<CentralPackageVersionOverrideEnabled>false</CentralPackageVersionOverrideEnabled>
</PropertyGroup>
<ItemGroup>
<GlobalPackageReference Include="ErrorProne.NET.CoreAnalyzers" Version="0.4.0-beta.1" />
<GlobalPackageReference Include="ErrorProne.NET.CoreAnalyzers" Version="0.7.0-beta.1" />
<GlobalPackageReference Include="Meziantou.Analyzer" Version="2.0.182" />
<GlobalPackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" />
<GlobalPackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.12.19" />
<GlobalPackageReference Include="PrimaryConstructorAnalyzer" Version="1.0.6" />
<GlobalPackageReference Include="Roslynator.Analyzers" Version="4.12.9" />
<GlobalPackageReference Include="SonarAnalyzer.CSharp" Version="10.3.0.106239" />
<GlobalPackageReference Include="Roslynator.Analyzers" Version="4.12.10" />
<GlobalPackageReference Include="SonarAnalyzer.CSharp" Version="10.4.0.108396" />
</ItemGroup>
<ItemGroup>
<PackageVersion Include="BenchmarkDotNet" Version="0.14.0" />
Expand All @@ -19,16 +19,14 @@
<PackageVersion Include="coverlet.collector" Version="6.0.2" />
<PackageVersion Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageVersion Include="EPPlusFree" Version="4.5.3.8" />
<PackageVersion Include="ErrorProne.NET.Structs" Version="0.4.0-beta.1" />
<PackageVersion Include="ErrorProne.NET.Structs" Version="0.6.1-beta.1" />
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="9.0.0" />
<PackageVersion Include="Microsoft.Bcl.HashCode" Version="6.0.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing" Version="1.1.2" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.9.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Polyfill" Version="6.2.0" />
<PackageVersion Include="PolySharp" Version="1.14.1" />
<PackageVersion Include="PublicApiGenerator" Version="11.2.0" />
<PackageVersion Include="PublicApiGenerator" Version="11.3.0" />
<PackageVersion Include="System.Collections.Immutable" Version="9.0.0" />
<PackageVersion Include="System.Drawing.Common" Version="4.7.3" />
<PackageVersion Include="System.Formats.Asn1" Version="9.0.0" />
Expand All @@ -38,10 +36,10 @@
<PackageVersion Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageVersion Include="TngTech.ArchUnitNET.xUnit" Version="0.11.1" />
<PackageVersion Include="Verify.SourceGenerators" Version="2.5.0" />
<PackageVersion Include="Verify.Xunit" Version="28.5.0" />
<PackageVersion Include="Verify.Xunit" Version="28.6.1" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.assert" Version="2.9.2" />
<PackageVersion Include="Xunit.Combinatorial" Version="1.6.24" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.0.0" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,6 @@ namespace SpreadCheetah.SourceGenerator.Extensions;

internal static class EnumerableExtensions
{
public static IEnumerable<(int Index, T Element)> Index<T>(this IEnumerable<T> elements)
{
return elements.Select((x, i) => (i, x));
}

public static EquatableArray<T> ToEquatableArray<T>(this IEnumerable<T> elements)
where T : IEquatable<T>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="all" />
<PackageReference Include="PolySharp">
<PackageReference Include="Polyfill">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,8 @@ namespace SpreadCheetah.SourceGeneration
public sealed class WorksheetRowGenerationOptionsAttribute : System.Attribute
{
public WorksheetRowGenerationOptionsAttribute() { }
[System.Obsolete("Configure rule severity in an .editorconfig file instead (e.g. \'dotnet_diagnostic" +
".SPCH1001.severity = none\').")]
[System.Obsolete(("Configure rule severity in an .editorconfig file instead (e.g. \'dotnet_diagnostic" +
".SPCH1001.severity = none\')."))]
public bool SuppressWarnings { get; set; }
}
public static class WorksheetRowMetadataServices
Expand Down Expand Up @@ -401,8 +401,8 @@ namespace SpreadCheetah.Styling
public const string Text = "@";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparator)")]
public const string ThousandsSeparator = "#,##0";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparatorTwoDecimalPlaces" +
")")]
[System.Obsolete(("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparatorTwoDecimalPlaces" +
")"))]
public const string ThousandsSeparatorTwoDecimalPlaces = "#,##0.00";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.TwoDecimalPlaces)")]
public const string TwoDecimalPlaces = "0.00";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,8 @@ namespace SpreadCheetah.SourceGeneration
public sealed class WorksheetRowGenerationOptionsAttribute : System.Attribute
{
public WorksheetRowGenerationOptionsAttribute() { }
[System.Obsolete("Configure rule severity in an .editorconfig file instead (e.g. \'dotnet_diagnostic" +
".SPCH1001.severity = none\').")]
[System.Obsolete(("Configure rule severity in an .editorconfig file instead (e.g. \'dotnet_diagnostic" +
".SPCH1001.severity = none\')."))]
public bool SuppressWarnings { get; set; }
}
public static class WorksheetRowMetadataServices
Expand Down Expand Up @@ -401,8 +401,8 @@ namespace SpreadCheetah.Styling
public const string Text = "@";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparator)")]
public const string ThousandsSeparator = "#,##0";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparatorTwoDecimalPlaces" +
")")]
[System.Obsolete(("Use NumberFormat.Standard(StandardNumberFormat.ThousandsSeparatorTwoDecimalPlaces" +
")"))]
public const string ThousandsSeparatorTwoDecimalPlaces = "#,##0.00";
[System.Obsolete("Use NumberFormat.Standard(StandardNumberFormat.TwoDecimalPlaces)")]
public const string TwoDecimalPlaces = "0.00";
Expand Down
98 changes: 61 additions & 37 deletions SpreadCheetah/MetadataXml/ContentTypesXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

namespace SpreadCheetah.MetadataXml;

internal struct ContentTypesXml : IXmlWriter
internal struct ContentTypesXml
{
public static ValueTask WriteAsync(
public static async ValueTask WriteAsync(
ZipArchive archive,
CompressionLevel compressionLevel,
SpreadsheetBuffer buffer,
Expand All @@ -17,8 +17,23 @@ public static ValueTask WriteAsync(
CancellationToken token)
{
var entry = archive.CreateEntry("[Content_Types].xml", compressionLevel);
var writer = new ContentTypesXml(worksheets, fileCounter, hasStylesXml);
return writer.WriteAsync(entry, buffer, token);
var stream = entry.Open();
#if NETSTANDARD2_0
using (stream)
#else
await using (stream.ConfigureAwait(false))
#endif
{
var writer = new ContentTypesXml(worksheets, fileCounter, hasStylesXml, buffer);

foreach (var success in writer)
{
if (!success)
await buffer.FlushToStreamAsync(stream, token).ConfigureAwait(false);
}

await buffer.FlushToStreamAsync(stream, token).ConfigureAwait(false);
}
}

private static ReadOnlySpan<byte> Header =>
Expand All @@ -41,121 +56,130 @@ public static ValueTask WriteAsync(

private readonly List<WorksheetMetadata> _worksheets;
private readonly FileCounter? _fileCounter;
private readonly SpreadsheetBuffer _buffer;
private readonly bool _hasStylesXml;
private Element _next;
private int _nextIndex;

private ContentTypesXml(List<WorksheetMetadata> worksheets, FileCounter? fileCounter, bool hasStylesXml)
private ContentTypesXml(
List<WorksheetMetadata> worksheets,
FileCounter? fileCounter,
bool hasStylesXml,
SpreadsheetBuffer buffer)
{
_worksheets = worksheets;
_fileCounter = fileCounter;
_hasStylesXml = hasStylesXml;
_buffer = buffer;
}

public bool TryWrite(Span<byte> bytes, out int bytesWritten)
{
bytesWritten = 0;

if (_next == Element.Header && !Advance(Header.TryCopyTo(bytes, ref bytesWritten))) return false;
if (_next == Element.ImageTypes && !Advance(TryWriteImageTypes(bytes, ref bytesWritten))) return false;
if (_next == Element.Vml && !Advance(TryWriteVml(bytes, ref bytesWritten))) return false;
if (_next == Element.Styles && !Advance(TryWriteStyles(bytes, ref bytesWritten))) return false;
if (_next == Element.Drawings && !Advance(TryWriteDrawings(bytes, ref bytesWritten))) return false;
if (_next == Element.Worksheets && !Advance(TryWriteWorksheets(bytes, ref bytesWritten))) return false;
if (_next == Element.Comments && !Advance(TryWriteComments(bytes, ref bytesWritten))) return false;
if (_next == Element.Footer && !Advance(Footer.TryCopyTo(bytes, ref bytesWritten))) return false;
public readonly ContentTypesXml GetEnumerator() => this;
public bool Current { get; private set; }

return true;
}

private bool Advance(bool success)
public bool MoveNext()
{
if (success)
Current = _next switch
{
Element.Header => _buffer.TryWrite(Header),
Element.ImageTypes => TryWriteImageTypes(),
Element.Vml => TryWriteVml(),
Element.Styles => TryWriteStyles(),
Element.Drawings => TryWriteDrawings(),
Element.Worksheets => TryWriteWorksheets(),
Element.Comments => TryWriteComments(),
_ => _buffer.TryWrite(Footer)
};

if (Current)
++_next;

return success;
return _next < Element.Done;
}

private readonly bool TryWriteImageTypes(Span<byte> bytes, ref int bytesWritten)
private readonly bool TryWriteImageTypes()
{
if (_fileCounter is not { } counter)
return true;

var bytes = _buffer.GetSpan();
var bytesWritten = 0;

if (counter.EmbeddedImageTypes.HasFlag(EmbeddedImageTypes.Png) && !Png.TryCopyTo(bytes, ref bytesWritten))
return false;

if (counter.EmbeddedImageTypes.HasFlag(EmbeddedImageTypes.Jpeg) && !Jpeg.TryCopyTo(bytes, ref bytesWritten))
return false;

_buffer.Advance(bytesWritten);
return true;
}

private readonly bool TryWriteStyles(Span<byte> bytes, ref int bytesWritten)
=> !_hasStylesXml || Styles.TryCopyTo(bytes, ref bytesWritten);
private readonly bool TryWriteStyles()
=> !_hasStylesXml || _buffer.TryWrite(Styles);

private bool TryWriteDrawings(Span<byte> bytes, ref int bytesWritten)
private bool TryWriteDrawings()
{
if (_fileCounter is not { } counter)
return true;

for (; _nextIndex < counter.WorksheetsWithImages; ++_nextIndex)
{
var span = bytes.Slice(bytesWritten);
var span = _buffer.GetSpan();
var written = 0;

if (!DrawingStart.TryCopyTo(span, ref written)) return false;
if (!SpanHelper.TryWrite(_nextIndex + 1, span, ref written)) return false;
if (!DrawingEnd.TryCopyTo(span, ref written)) return false;

bytesWritten += written;
_buffer.Advance(written);
}

_nextIndex = 0;
return true;
}

private readonly bool TryWriteVml(Span<byte> bytes, ref int bytesWritten)
private readonly bool TryWriteVml()
{
var hasNotes = _fileCounter is { WorksheetsWithNotes: > 0 };
return !hasNotes || Vml.TryCopyTo(bytes, ref bytesWritten);
return !hasNotes || _buffer.TryWrite(Vml);
}

private bool TryWriteWorksheets(Span<byte> bytes, ref int bytesWritten)
private bool TryWriteWorksheets()
{
var worksheets = _worksheets;

for (; _nextIndex < worksheets.Count; ++_nextIndex)
{
var worksheet = worksheets[_nextIndex];
var span = bytes.Slice(bytesWritten);
var span = _buffer.GetSpan();
var written = 0;

if (!SheetStart.TryCopyTo(span, ref written)) return false;
if (!SpanHelper.TryWrite(worksheet.Path, span, ref written)) return false;
if (!SheetEnd.TryCopyTo(span, ref written)) return false;

bytesWritten += written;
_buffer.Advance(written);
}

_nextIndex = 0;
return true;
}

private bool TryWriteComments(Span<byte> bytes, ref int bytesWritten)
private bool TryWriteComments()
{
if (_fileCounter is not { } counter)
return true;

for (; _nextIndex < counter.WorksheetsWithNotes; ++_nextIndex)
{
var span = bytes.Slice(bytesWritten);
var span = _buffer.GetSpan();
var written = 0;

if (!CommentStart.TryCopyTo(span, ref written)) return false;
if (!SpanHelper.TryWrite(_nextIndex + 1, span, ref written)) return false;
if (!CommentEnd.TryCopyTo(span, ref written)) return false;

bytesWritten += written;
_buffer.Advance(written);
}

_nextIndex = 0;
Expand Down
Loading