Skip to content

Commit

Permalink
fix: ignore static fields and properties (#380)
Browse files Browse the repository at this point in the history
  • Loading branch information
latonz committed Apr 27, 2023
1 parent 515c27a commit e5e2d1c
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Riok.Mapperly/Helpers/SymbolExtensions.cs
Expand Up @@ -60,12 +60,17 @@ internal static IEnumerable<ISymbol> GetAllMembers(this ITypeSymbol symbol)
IEqualityComparer<string> comparer
)
{
return symbol.GetAllMembers().Where(x => comparer.Equals(name, x.Name) && !x.IsStatic).Select(MappableMember.Create).WhereNotNull();
return symbol.GetAllMembers().Where(x => !x.IsStatic && comparer.Equals(name, x.Name)).Select(MappableMember.Create).WhereNotNull();
}

internal static IEnumerable<IMappableMember> GetAccessibleMappableMembers(this ITypeSymbol symbol)
{
return symbol.GetAllMembers().Where(x => x.IsAccessible()).DistinctBy(x => x.Name).Select(MappableMember.Create).WhereNotNull();
return symbol
.GetAllMembers()
.Where(x => !x.IsStatic && x.IsAccessible())
.DistinctBy(x => x.Name)
.Select(MappableMember.Create)
.WhereNotNull();
}

internal static IMethodSymbol? GetStaticGenericMethod(this INamedTypeSymbol namedType, string methodName)
Expand Down
22 changes: 22 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/ObjectFieldTest.cs
Expand Up @@ -45,4 +45,26 @@ public void StringToIntField()
"""
);
}

[Fact]
public void ShouldIgnoreStaticField()
{
var source = TestSourceBuilder.Mapping(
"A",
"B",
"class A { public string Name; public static string Value; }",
"class B { public string Name; public static string Value; }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
target.Name = source.Name;
return target;
"""
);
}
}
22 changes: 22 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/ObjectPropertyTest.cs
Expand Up @@ -391,4 +391,26 @@ public void UnmappedReadOnlyTargetPropertyShouldNotDiagnostic()
"""
);
}

[Fact]
public void ShouldIgnoreStaticProperty()
{
var source = TestSourceBuilder.Mapping(
"A",
"B",
"class A { public string Name { get; } public static string Value { get; } }",
"class B { public string Name { set; } public static string Value { set; } }"
);

TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody(
"""
var target = new global::B();
target.Name = source.Name;
return target;
"""
);
}
}

0 comments on commit e5e2d1c

Please sign in to comment.