This repository was archived by the owner on Dec 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathFrameworkInfoProviderGenerator.cs
54 lines (50 loc) · 2.55 KB
/
FrameworkInfoProviderGenerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CodeGeneration.Roslyn;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace BuildPropsGenerator
{
public class FrameworkInfoProviderGenerator : ICodeGenerator
{
public FrameworkInfoProviderGenerator(AttributeData attributeData)
{
}
public Task<SyntaxList<MemberDeclarationSyntax>> GenerateAsync(TransformationContext context, IProgress<Diagnostic> progress, CancellationToken cancellationToken)
{
var partialType = CreatePartialType();
return Task.FromResult(SyntaxFactory.List(partialType));
IEnumerable<MemberDeclarationSyntax> CreatePartialType()
{
var newPartialType =
context.ProcessingNode is ClassDeclarationSyntax classDeclaration
? SyntaxFactory.ClassDeclaration(classDeclaration.Identifier.ValueText)
: context.ProcessingNode is StructDeclarationSyntax structDeclaration
? SyntaxFactory.StructDeclaration(structDeclaration.Identifier.ValueText)
: default(TypeDeclarationSyntax);
if (newPartialType is null)
yield break;
yield return newPartialType
?.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword))
.AddMembers(CreateTargetFrameworkListProperty(), CreateCurrentTargetFrameworkProperty());
}
MemberDeclarationSyntax CreateTargetFrameworkListProperty()
{
var collectionType = "System.Collections.Generic.List<string>";
var frameworks = context.BuildProperties["TargetFrameworks"];
var quotedFrameworks = frameworks.Split(";").Select(framework => $"\"{framework}\"");
var commaDelimitedFrameworks = string.Join(',', quotedFrameworks.ToArray());
return SyntaxFactory.ParseMemberDeclaration($"public {collectionType} TargetFrameworks {{ get; }} = new {collectionType} {{ {commaDelimitedFrameworks} }};");
}
MemberDeclarationSyntax CreateCurrentTargetFrameworkProperty()
{
var framework = context.BuildProperties["TargetFramework"];
return SyntaxFactory.ParseMemberDeclaration($"public string CurrentTargetFramework {{ get; }} = \"{framework}\";");
}
}
}
}