forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateGlobalUsings.cs
117 lines (96 loc) · 3.35 KB
/
GenerateGlobalUsings.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
namespace Microsoft.NET.Build.Tasks
{
public sealed class GenerateGlobalUsings : TaskBase
{
[Required]
public ITaskItem[] Usings { get; set; }
[Output]
public string[] Lines { get; set; }
protected override void ExecuteCore()
{
if (Usings.Length == 0)
{
Lines = Array.Empty<string>();
return;
}
var usings = Usings.Select(UsingInfo.Read)
.OrderBy(static k => k, UsingInfoComparer.Instance)
.Distinct(UsingInfoComparer.Instance);
var lines = new string[Usings.Length + 1];
lines[0] = "// <auto-generated/>";
var index = 1;
var lineBuilder = new StringBuilder();
foreach (var @using in usings)
{
lineBuilder.Clear();
lineBuilder.Append("global using ");
if (@using.Static)
{
lineBuilder.Append("static ");
}
if (!string.IsNullOrEmpty(@using.Alias))
{
lineBuilder.Append(@using.Alias)
.Append(" = ");
}
lineBuilder.Append("global::")
.Append(@using.Namespace)
.Append(';');
lines[index++] = lineBuilder.ToString();
}
Lines = lines;
}
private readonly struct UsingInfo
{
public static UsingInfo Read(ITaskItem taskItem)
{
return new UsingInfo(
taskItem.ItemSpec,
taskItem.GetBooleanMetadata("Static") == true,
taskItem.GetMetadata("Alias"));
}
private UsingInfo(string @namespace, bool @static, string alias)
{
Namespace = @namespace;
Static = @static;
Alias = alias;
}
public string Namespace { get; }
public bool Static { get; }
public string Alias { get; }
}
private sealed class UsingInfoComparer : IComparer<UsingInfo>, IEqualityComparer<UsingInfo>
{
public static readonly UsingInfoComparer Instance = new();
public int Compare(UsingInfo x, UsingInfo y)
{
var @static = x.Static.CompareTo(y.Static);
if (@static != 0)
{
return @static;
}
var alias = x.Alias.CompareTo(y.Alias);
if (alias != 0)
{
return alias;
}
return StringComparer.Ordinal.Compare(x.Namespace, y.Namespace);
}
public bool Equals(UsingInfo x, UsingInfo y)
{
return Compare(x, y) == 0;
}
public int GetHashCode(UsingInfo obj)
{
return StringComparer.Ordinal.GetHashCode(obj.Namespace);
}
}
}
}