Skip to content

Commit

Permalink
fix: only diagnostic missing member mappings for required init members (
Browse files Browse the repository at this point in the history
  • Loading branch information
latonz authored Jan 20, 2025
1 parent d397ef2 commit c7df8fd
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,18 @@ public static void BuildInitMemberMappings(
// set the member mapped as it is an init only member
// diagnostics are already reported
// and no further mapping attempts should be undertaken
ctx.BuilderContext.ReportDiagnostic(
targetMember.IsRequired ? DiagnosticDescriptors.RequiredMemberNotMapped : DiagnosticDescriptors.SourceMemberNotFound,
targetMember.Name,
ctx.Mapping.TargetType,
ctx.Mapping.SourceType
);
if (
targetMember.IsRequired
|| ctx.BuilderContext.Configuration.Members.RequiredMappingStrategy.HasFlag(RequiredMappingStrategy.Target)
)
{
ctx.BuilderContext.ReportDiagnostic(
targetMember.IsRequired ? DiagnosticDescriptors.RequiredMemberNotMapped : DiagnosticDescriptors.SourceMemberNotFound,
targetMember.Name,
ctx.Mapping.TargetType,
ctx.Mapping.SourceType
);
}
ctx.SetTargetMemberMapped(targetMember);
}
}
Expand Down
32 changes: 32 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/ObjectPropertyInitPropertyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -489,4 +489,36 @@ public record B : BBase
"""
);
}

[Fact]
public void InitOnlyPropertyWithSourceRequiredMappingShouldOnlyDiagnosticForRequired()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"""
[MapperRequiredMapping(RequiredMappingStrategy.Source)]
partial B Map(A source);
""",
"""
public record A(int Value);
public class B { public int Value { get; init; } public required int Value2 { get; init; } public int Value3 { get; init; } }
"""
);
TestHelper
.GenerateMapper(source, TestHelperOptions.AllowDiagnostics)
.Should()
.HaveMapMethodBody(
"""
var target = new global::B()
{
Value = source.Value,
};
return target;
"""
)
.HaveDiagnostic(
DiagnosticDescriptors.RequiredMemberNotMapped,
"Required member Value2 on mapping target type B was not found on the mapping source type A"
)
.HaveAssertedAllDiagnostics();
}
}

0 comments on commit c7df8fd

Please sign in to comment.