Skip to content

Commit

Permalink
GenerateMapper setting, apply ExplicitMapping to AdaptAttribute, fix …
Browse files Browse the repository at this point in the history
…tool duplicate name
  • Loading branch information
chaowlert committed Nov 5, 2020
1 parent 0bcafbb commit 859661e
Show file tree
Hide file tree
Showing 14 changed files with 119 additions and 36 deletions.
2 changes: 1 addition & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"mapster.tool": {
"version": "2.0.47",
"version": "6.5.2",
"commands": [
"dotnet-mapster"
]
Expand Down
22 changes: 4 additions & 18 deletions src/Mapster.Core/Attributes/BaseAdaptAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,28 +31,14 @@ protected BaseAdaptAttribute(string name)

public class AdaptFromAttribute : BaseAdaptAttribute
{
public AdaptFromAttribute(Type type) : base(type)
{
this.MapType = MapType.Map | MapType.MapToTarget;
}

public AdaptFromAttribute(string name) : base(name)
{
this.MapType = MapType.Map | MapType.MapToTarget;
}
public AdaptFromAttribute(Type type) : base(type) { }
public AdaptFromAttribute(string name) : base(name) { }
}

public class AdaptToAttribute : BaseAdaptAttribute
{
public AdaptToAttribute(Type type) : base(type)
{
this.MapType = MapType.Map | MapType.MapToTarget | MapType.Projection;
}

public AdaptToAttribute(string name) : base(name)
{
this.MapType = MapType.Map | MapType.MapToTarget | MapType.Projection;
}
public AdaptToAttribute(Type type) : base(type) { }
public AdaptToAttribute(string name) : base(name) { }
}

public class AdaptTwoWaysAttribute : AdaptToAttribute
Expand Down
4 changes: 2 additions & 2 deletions src/Mapster.Tool/Mapster.Tool.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>Mapster.Tool.snk</AssemblyOriginatorKeyFile>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>6.5.1</Version>
<Version>6.5.2</Version>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Copyright>Copyright (c) 2020 Chaowlert Chaisrichalermpol</Copyright>
<PackageIcon>icon.png</PackageIcon>
Expand All @@ -30,7 +30,7 @@

<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.8.0" />
<PackageReference Include="ExpressionTranslator" Version="2.3.1" />
<PackageReference Include="ExpressionTranslator" Version="2.3.2" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.1.6" />
</ItemGroup>

Expand Down
31 changes: 24 additions & 7 deletions src/Mapster.Tool/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,15 +252,20 @@ private static void GenerateExtensions(ExtensionOptions opt)
var attrs = type.SafeGetCustomAttributes();
var mapperAttr = attrs.OfType<GenerateMapperAttribute>()
.FirstOrDefault();
if (mapperAttr == null)
var ruleMaps = config.RuleMap
.Where(it => it.Key.Source == type &&
it.Value.Settings.GenerateMapper is MapType)
.ToList();
if (mapperAttr == null && ruleMaps.Count == 0)
continue;

mapperAttr ??= new GenerateMapperAttribute();
var set = mapperAttr.ForAttributes?.ToHashSet();
var adaptAttrs = attrs
.OfType<BaseAdaptAttribute>()
.Where(it => set?.Contains(it.GetType()) != false)
.ToList();
if (adaptAttrs.Count == 0)
if (adaptAttrs.Count == 0 && ruleMaps.Count == 0)
continue;

Console.WriteLine($"Processing: {type.FullName}");
Expand Down Expand Up @@ -289,7 +294,8 @@ private static void GenerateExtensions(ExtensionOptions opt)
continue;

var tuple = new TypeTuple(fromType, type);
GenerateExtensionMethods(attr.MapType, config, tuple, translator, type, mapperAttr.IsHelperClass);
var mapType = attr.MapType == 0 ? MapType.Map | MapType.MapToTarget : attr.MapType;
GenerateExtensionMethods(mapType, config, tuple, translator, type, mapperAttr.IsHelperClass);
}

if (attr is AdaptToAttribute)
Expand All @@ -308,10 +314,17 @@ private static void GenerateExtensions(ExtensionOptions opt)
continue;

var tuple = new TypeTuple(type, toType);
GenerateExtensionMethods(attr.MapType, config, tuple, translator, type, mapperAttr.IsHelperClass);
var mapType = attr.MapType == 0 ? MapType.Map | MapType.MapToTarget | MapType.Projection : attr.MapType;
GenerateExtensionMethods(mapType, config, tuple, translator, type, mapperAttr.IsHelperClass);
}
}

foreach (var (tuple, rule) in ruleMaps)
{
var mapType = (MapType) rule.Settings.GenerateMapper!;
GenerateExtensionMethods(mapType, config, tuple, translator, type, mapperAttr.IsHelperClass);
}

var code = translator.ToString();
var path = Path.Combine(Path.GetFullPath(opt.Output), definitions.TypeName + ".g.cs");
WriteFile(code, path);
Expand All @@ -321,9 +334,13 @@ private static void GenerateExtensions(ExtensionOptions opt)
private static void GenerateExtensionMethods(MapType mapType, TypeAdapterConfig config, TypeTuple tuple,
ExpressionTranslator translator, Type entityType, bool isHelperClass)
{
var name = tuple.Destination == entityType
? "Entity"
: tuple.Destination.Name.Replace(entityType.Name, "");
//add type name to prevent duplication
translator.Translate(entityType);
var destName = translator.Translate(tuple.Destination);

var name = tuple.Destination.Name == entityType.Name
? destName
: destName.Replace(entityType.Name, "");
if ((mapType & MapType.Map) > 0)
{
var expr = config.CreateMapExpression(tuple, MapType.Map);
Expand Down
3 changes: 2 additions & 1 deletion src/Mapster.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
..\.config\dotnet-tools.json = ..\.config\dotnet-tools.json
global.json = global.json
..\LICENSE = ..\LICENSE
..\README.md = ..\README.md
EndProjectSection
Expand Down Expand Up @@ -53,7 +54,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Samples", "Samples", "{EF7E
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mapster.SourceGenerator", "Mapster.SourceGenerator\Mapster.SourceGenerator.csproj", "{BFAFD4DF-7530-46EA-866E-C2A74DAEBDB1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mapster.Core", "Mapster.Core\Mapster.Core.csproj", "{1A7D2FD4-DDEC-4E11-93FF-1310F34F67CF}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mapster.Core", "Mapster.Core\Mapster.Core.csproj", "{1A7D2FD4-DDEC-4E11-93FF-1310F34F67CF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
17 changes: 13 additions & 4 deletions src/Mapster/TypeAdapterConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -497,9 +497,10 @@ where typeof(AdaptToAttribute).IsAssignableFrom(o.GetAttributeType())
return rules1;
var rules2 = from type in tuple.Destination.GetAllTypes()
from o in type.GetTypeInfo().GetCustomAttributesData()
where typeof(BaseAdaptAttribute).IsAssignableFrom(o.GetAttributeType())
where typeof(AdaptFromAttribute).IsAssignableFrom(o.GetAttributeType()) ||
typeof(AdaptTwoWaysAttribute).IsAssignableFrom(o.GetAttributeType())
let attr = o.CreateCustomAttribute<BaseAdaptAttribute>()
where attr != null && (attr.MapType & mapType) != 0 && (attr is AdaptFromAttribute || attr is AdaptTwoWaysAttribute)
where attr != null && (attr.MapType & mapType) != 0
where attr.Type == null || attr.Type == tuple.Source
where attr.Name == null || attr.Name.Replace("[name]", type.Name) == tuple.Source.Name
let distance = GetSubclassDistance(tuple.Destination, type, true)
Expand Down Expand Up @@ -553,11 +554,19 @@ internal TypeAdapterSettings GetMergedSettings(TypeTuple tuple, MapType mapType)
MapType = mapType,
ExplicitMapping = this.RuleMap.ContainsKey(tuple),
};

//auto add setting if there is attr setting
var attrSettings = GetAttributeSettings(tuple, mapType).ToList();
if (!arg.ExplicitMapping && attrSettings.Any(rule => rule.Priority(arg) == 100))
{
GetSettings(tuple);
arg.ExplicitMapping = true;
}

var result = new TypeAdapterSettings();
lock (this.Rules)
{
var rules = this.Rules.Reverse<TypeAdapterRule>()
.Concat(GetAttributeSettings(tuple, mapType));
var rules = this.Rules.Reverse<TypeAdapterRule>().Concat(attrSettings);
var settings = from rule in rules
let priority = rule.Priority(arg)
where priority != null
Expand Down
15 changes: 15 additions & 0 deletions src/Mapster/TypeAdapterSetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,14 @@ internal TypeAdapterSetter(TypeAdapterSettings settings, TypeAdapterConfig paren
return this;
}

public TypeAdapterSetter<TSource, TDestination> GenerateMapper(MapType mapType)
{
this.CheckCompiled();

Settings.GenerateMapper = mapType;
return this;
}

public TwoWaysTypeAdapterSetter<TSource, TDestination> TwoWays()
{
return new TwoWaysTypeAdapterSetter<TSource, TDestination>(this.Config);
Expand Down Expand Up @@ -879,5 +887,12 @@ public TwoWaysTypeAdapterSetter(TypeAdapterConfig config)
DestinationToSourceSetter.Fork(action);
return this;
}

public TwoWaysTypeAdapterSetter<TSource, TDestination> GenerateMapper(MapType mapType)
{
SourceToDestinationSetter.GenerateMapper(mapType);
DestinationToSourceSetter.GenerateMapper(mapType);
return this;
}
}
}
5 changes: 5 additions & 0 deletions src/Mapster/TypeAdapterSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ public NameMatchingStrategy NameMatchingStrategy
get => Get(nameof(EnableNonPublicMembers));
set => Set(nameof(EnableNonPublicMembers), value);
}
public object? GenerateMapper
{
get => Get<object>(nameof(GenerateMapper));
set => Set(nameof(GenerateMapper), value);
}

public List<Func<IMemberModel, MemberSide, bool?>> ShouldMapMember
{
Expand Down
2 changes: 1 addition & 1 deletion src/Sample.CodeGen/Controllers/SchoolController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public IQueryable<Person> GetStudents()
[HttpPost("student")]
public async Task AddStudent([FromBody] StudentAdd data)
{
var student = data.AdaptToEntity();
var student = data.AdaptToStudent();
_context.Students.Add(student);
await _context.SaveChangesAsync();
}
Expand Down
14 changes: 14 additions & 0 deletions src/Sample.CodeGen/MappingRegister.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Mapster;
using Sample.CodeGen.Models;

namespace Sample.CodeGen
{
public class MappingRegister : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.ForType<Person, Person>()
.GenerateMapper(MapType.Map | MapType.MapToTarget);
}
}
}
2 changes: 1 addition & 1 deletion src/Sample.CodeGen/Models/CourseMapper.g.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static CourseDto AdaptTo(this Course p3, CourseDto p4)
}
}).ToList<EnrollmentDto>()
};
public static Course AdaptToEntity(this CourseAdd p9)
public static Course AdaptToCourse(this CourseAdd p9)
{
return p9 == null ? null : new Course()
{
Expand Down
31 changes: 31 additions & 0 deletions src/Sample.CodeGen/Models/PersonMapper.g.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Sample.CodeGen.Models;

namespace Sample.CodeGen.Models
{
public static partial class PersonMapper
{
public static Person AdaptToPerson(this Person p1)
{
return p1 == null ? null : new Person()
{
ID = p1.ID,
LastName = p1.LastName,
FirstMidName = p1.FirstMidName
};
}
public static Person AdaptTo(this Person p2, Person p3)
{
if (p2 == null)
{
return null;
}
Person result = p3 ?? new Person();

result.ID = p2.ID;
result.LastName = p2.LastName;
result.FirstMidName = p2.FirstMidName;
return result;

}
}
}
2 changes: 1 addition & 1 deletion src/Sample.CodeGen/Models/StudentMapper.g.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static StudentDto AdaptTo(this Student p2, StudentDto p3)
FirstMidName = p4.FirstMidName,
EnrollmentDate = p4.EnrollmentDate
};
public static Student AdaptToEntity(this StudentAdd p5)
public static Student AdaptToStudent(this StudentAdd p5)
{
return p5 == null ? null : new Student()
{
Expand Down
5 changes: 5 additions & 0 deletions src/global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"sdk": {
"version": "3.1.403"
}
}

0 comments on commit 859661e

Please sign in to comment.