Skip to content

Commit

Permalink
Merge pull request #71 from sveinungf/dev/src-gen-cellstyle
Browse files Browse the repository at this point in the history
Source generator - Attribute for named style
  • Loading branch information
sveinungf authored Sep 1, 2024
2 parents 956b7fb + bafeaeb commit 4e8ef39
Show file tree
Hide file tree
Showing 95 changed files with 2,703 additions and 966 deletions.
5 changes: 4 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ dotnet_diagnostic.IDE0301.severity = warning
# IDE0305: Use collection expression for fluent
dotnet_diagnostic.IDE0305.severity = warning

[{CellValueTruncateAttribute.cs,ColumnHeaderAttribute.cs,ColumnOrderAttribute.cs,ColumnWidthAttribute.cs,WorksheetRowAttribute.cs}]
[{CellValueTruncateAttribute.cs,ColumnHeaderAttribute.cs,ColumnOrderAttribute.cs,CellStyleAttribute.cs,ColumnWidthAttribute.cs,WorksheetRowAttribute.cs}]
# CA1019: Define accessors for attribute arguments
dotnet_diagnostic.CA1019.severity = none
# CS9113: Parameter is unread
Expand Down Expand Up @@ -244,6 +244,9 @@ dotnet_diagnostic.MA0076.severity = none
# RCS1163: Unused parameter
dotnet_diagnostic.RCS1163.severity = warning

# RCS1205: Order named arguments according to the order of parameters
dotnet_diagnostic.RCS1205.severity = none

[{ColumnHeaderAttribute.cs,ColumnOrderAttribute.cs,WorksheetRowAttribute.cs}]
# RCS1163: Unused parameter
dotnet_diagnostic.RCS1163.severity = none
Expand Down
3 changes: 1 addition & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
<PackageVersion Include="Microsoft.Bcl.AsyncInterfaces" Version="1.1.1" />
<PackageVersion Include="Microsoft.Bcl.HashCode" Version="1.1.1" />
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.7.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.9.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.11.0" />
<PackageVersion Include="Polyfill" Version="6.2.0" />
<PackageVersion Include="PolySharp" Version="1.14.1" />
Expand Down
1 change: 0 additions & 1 deletion SpreadCheetah.Benchmark/SpreadCheetah.Benchmark.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
<PackageReference Include="ClosedXML" />
<PackageReference Include="DocumentFormat.OpenXml" />
<PackageReference Include="EPPlusFree" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" />
<PackageReference Include="Polyfill">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
namespace SpreadCheetah.SourceGenerator.CSharp8Test.Models
using SpreadCheetah.SourceGeneration;

namespace SpreadCheetah.SourceGenerator.CSharp8Test.Models
{
public class BaseClass
{
[CellStyle("Id style")]
public string Id { get; }

protected BaseClass(string id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ namespace SpreadCheetah.SourceGenerator.CSharp8Test.Models
public class ClassWithMultipleProperties : BaseClass
{
[ColumnHeader("Last name")]
[CellStyle("Last name style")]
[CellValueTruncate(20)]
public string LastName { get; }

[ColumnOrder(1)]
public string FirstName { get; }

[ColumnWidth(5)]
public int Age { get; }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SpreadCheetah.SourceGenerator.CSharp8Test.Models;
using SpreadCheetah.Styling;
using SpreadCheetah.TestHelpers.Assertions;
using System;
using System.IO;
Expand All @@ -24,6 +25,8 @@ public async Task Spreadsheet_AddAsRow_ClassWithMultipleProperties()
await using (var spreadsheet = await Spreadsheet.CreateNewAsync(stream))
{
await spreadsheet.StartWorksheetAsync("Sheet", ctx);
spreadsheet.AddStyle(new Style { Font = { Bold = true } }, "Id style");
spreadsheet.AddStyle(new Style { Font = { Italic = true } }, "Last name style");

// Act
await spreadsheet.AddAsRowAsync(obj, ctx);
Expand All @@ -39,6 +42,9 @@ public async Task Spreadsheet_AddAsRow_ClassWithMultipleProperties()
Assert.Equal(obj.Age, sheet["D1"].IntValue);
Assert.Equal(4, sheet.CellCount);
Assert.Equal(5, sheet.Column("D").Width, 4);

Assert.True(sheet["B1"].Style.Font.Bold);
Assert.True(sheet["C1"].Style.Font.Italic);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ private static PortableExecutableReference[] GetAssemblyReferences()
];
}

public static SettingsTask CompileAndVerify<T>(string source, bool replaceEscapedLineEndings = false, params object?[] parameters) where T : IIncrementalGenerator, new()
public static SettingsTask CompileAndVerify<T>(string source,
bool replaceEscapedLineEndings = false,
bool onlyDiagnostics = false,
params object?[] parameters) where T : IIncrementalGenerator, new()
{
var syntaxTree = CSharpSyntaxTree.ParseText(source);
var references = GetAssemblyReferences();
Expand All @@ -47,6 +50,9 @@ private static PortableExecutableReference[] GetAssemblyReferences()

var task = Verify(target, settings);

if (onlyDiagnostics)
task = task.IgnoreGeneratedResult(x => x.SourceText.ToString().Contains("public WorksheetRowTypeInfo<", StringComparison.Ordinal));

return parameters.Length > 0
? task.UseParameters(parameters)
: task;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
Diagnostics: [
{
Id: SPCH1006,
Title: Invalid attribute argument,
Severity: Error,
WarningLevel: 0,
Location: : (6,5)-(6,18),
MessageFormat: '{0}' is an invalid argument for attribute '{1}',
Message: '' is an invalid argument for attribute 'SpreadCheetah.SourceGeneration.CellStyleAttribute',
Category: SpreadCheetah.SourceGenerator
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//HintName: MyNamespace.MyGenRowContext.g.cs
// <auto-generated />
#nullable enable
using SpreadCheetah;
using SpreadCheetah.SourceGeneration;
using SpreadCheetah.Styling;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace MyNamespace
{
public partial class MyGenRowContext
{
private static MyGenRowContext? _default;
public static MyGenRowContext Default => _default ??= new MyGenRowContext();

public MyGenRowContext()
{
}

private WorksheetRowTypeInfo<MyNamespace.ClassWithCellStyle>? _ClassWithCellStyle;
public WorksheetRowTypeInfo<MyNamespace.ClassWithCellStyle> ClassWithCellStyle => _ClassWithCellStyle
??= WorksheetRowMetadataServices.CreateObjectInfo<MyNamespace.ClassWithCellStyle>(
AddHeaderRow0Async, AddAsRowAsync, AddRangeAsRowsAsync, null, CreateWorksheetRowDependencyInfo0);

private static WorksheetRowDependencyInfo CreateWorksheetRowDependencyInfo0(Spreadsheet spreadsheet)
{
var styleIds = new[]
{
spreadsheet.GetStyleId("Italic"),
spreadsheet.GetStyleId("Bold"),
};
return new WorksheetRowDependencyInfo(styleIds);
}

private static async ValueTask AddHeaderRow0Async(SpreadCheetah.Spreadsheet spreadsheet, SpreadCheetah.Styling.StyleId? styleId, CancellationToken token)
{
var cells = ArrayPool<StyledCell>.Shared.Rent(4);
try
{
cells[0] = new StyledCell("FirstName", styleId);
cells[1] = new StyledCell("LastName", styleId);
cells[2] = new StyledCell("YearOfBirth", styleId);
cells[3] = new StyledCell("Initials", styleId);
await spreadsheet.AddRowAsync(cells.AsMemory(0, 4), token).ConfigureAwait(false);
}
finally
{
ArrayPool<StyledCell>.Shared.Return(cells, true);
}
}

private static ValueTask AddAsRowAsync(SpreadCheetah.Spreadsheet spreadsheet, MyNamespace.ClassWithCellStyle? obj, CancellationToken token)
{
if (spreadsheet is null)
throw new ArgumentNullException(nameof(spreadsheet));
if (obj is null)
return spreadsheet.AddRowAsync(ReadOnlyMemory<StyledCell>.Empty, token);
return AddAsRowInternalAsync(spreadsheet, obj, token);
}

private static ValueTask AddRangeAsRowsAsync(SpreadCheetah.Spreadsheet spreadsheet,
IEnumerable<MyNamespace.ClassWithCellStyle?> objs,
CancellationToken token)
{
if (spreadsheet is null)
throw new ArgumentNullException(nameof(spreadsheet));
if (objs is null)
throw new ArgumentNullException(nameof(objs));
return AddRangeAsRowsInternalAsync(spreadsheet, objs, token);
}

private static async ValueTask AddAsRowInternalAsync(SpreadCheetah.Spreadsheet spreadsheet,
MyNamespace.ClassWithCellStyle obj,
CancellationToken token)
{
var cells = ArrayPool<StyledCell>.Shared.Rent(4);
try
{
var worksheetRowDependencyInfo = spreadsheet.GetOrCreateWorksheetRowDependencyInfo(Default.ClassWithCellStyle);
var styleIds = worksheetRowDependencyInfo.StyleIds;
await AddCellsAsRowAsync(spreadsheet, obj, cells, styleIds, token).ConfigureAwait(false);
}
finally
{
ArrayPool<StyledCell>.Shared.Return(cells, true);
}
}

private static async ValueTask AddRangeAsRowsInternalAsync(SpreadCheetah.Spreadsheet spreadsheet,
IEnumerable<MyNamespace.ClassWithCellStyle?> objs,
CancellationToken token)
{
var cells = ArrayPool<StyledCell>.Shared.Rent(4);
try
{
var worksheetRowDependencyInfo = spreadsheet.GetOrCreateWorksheetRowDependencyInfo(Default.ClassWithCellStyle);
var styleIds = worksheetRowDependencyInfo.StyleIds;
foreach (var obj in objs)
{
await AddCellsAsRowAsync(spreadsheet, obj, cells, styleIds, token).ConfigureAwait(false);
}
}
finally
{
ArrayPool<StyledCell>.Shared.Return(cells, true);
}
}

private static ValueTask AddCellsAsRowAsync(SpreadCheetah.Spreadsheet spreadsheet,
MyNamespace.ClassWithCellStyle? obj,
StyledCell[] cells, IReadOnlyList<StyleId> styleIds, CancellationToken token)
{
if (obj is null)
return spreadsheet.AddRowAsync(ReadOnlyMemory<StyledCell>.Empty, token);

cells[0] = new StyledCell(new DataCell(obj.FirstName), styleIds[0]);
cells[1] = new StyledCell(new DataCell(obj.LastName), styleIds[1]);
cells[2] = new StyledCell(new DataCell(obj.YearOfBirth), null);
cells[3] = new StyledCell(new DataCell(obj.Initials), styleIds[1]);
return spreadsheet.AddRowAsync(cells.AsMemory(0, 4), token);
}

private static DataCell ConstructTruncatedDataCell(string? value, int truncateLength)
{
return value is null || value.Length <= truncateLength
? new DataCell(value)
: new DataCell(value.AsMemory(0, truncateLength));
}
}
}
Loading

0 comments on commit 4e8ef39

Please sign in to comment.