forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDotnetAddPostActionProcessor.cs
212 lines (190 loc) · 9.07 KB
/
DotnetAddPostActionProcessor.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.DotNet.Cli.Utils;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem;
using Microsoft.TemplateEngine.Cli.PostActionProcessors;
using Microsoft.TemplateEngine.Utils;
namespace Microsoft.DotNet.Tools.New.PostActionProcessors;
internal class DotnetAddPostActionProcessor : PostActionProcessorBase
{
private readonly Func<string, string, string?, bool> _addPackageReferenceCallback;
private readonly Func<string, string, bool> _addProjectReferenceCallback;
public DotnetAddPostActionProcessor(
Func<string, string, string?, bool>? addPackageReferenceCallback = null,
Func<string, string, bool>? addProjectReferenceCallback = null)
{
_addPackageReferenceCallback = addPackageReferenceCallback ?? DotnetCommandCallbacks.AddPackageReference;
_addProjectReferenceCallback = addProjectReferenceCallback ?? DotnetCommandCallbacks.AddProjectReference;
}
public override Guid Id => ActionProcessorId;
internal static Guid ActionProcessorId { get; } = new("B17581D1-C5C9-4489-8F0A-004BE667B814");
internal static IReadOnlyList<string> FindProjFileAtOrAbovePath(IPhysicalFileSystem fileSystem, string startPath, HashSet<string> extensionLimiters)
{
if (extensionLimiters.Count == 0)
{
return FileFindHelpers.FindFilesAtOrAbovePath(fileSystem, startPath, "*.*proj");
}
else
{
return FileFindHelpers.FindFilesAtOrAbovePath(fileSystem, startPath, "*.*proj", (filename) => extensionLimiters.Contains(Path.GetExtension(filename)));
}
}
protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
{
IReadOnlyList<string>? projectsToProcess = GetConfiguredFiles(action.Args, creationEffects, "targetFiles", outputBasePath);
if (!projectsToProcess.Any())
{
//If the author didn't opt in to the new behavior by specifying "targetFiles", search for project file in current output directory or above.
HashSet<string> extensionLimiters = new(StringComparer.Ordinal);
if (action.Args.TryGetValue("projectFileExtensions", out string? projectFileExtensions))
{
if (projectFileExtensions.Contains('/') || projectFileExtensions.Contains('\\') || projectFileExtensions.Contains('*'))
{
// these must be literals
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ActionMisconfigured);
return false;
}
extensionLimiters.UnionWith(projectFileExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
projectsToProcess = TryFindProjects(environment, outputBasePath, extensionLimiters);
if (projectsToProcess.Count > 1)
{
// multiple projects at the same level. Error.
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_UnresolvedProjFile);
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ProjFileListHeader);
foreach (string projectFile in projectsToProcess)
{
Reporter.Error.WriteLine(string.Format("\t{0}", projectFile));
}
return false;
}
}
if (!projectsToProcess.Any())
{
projectsToProcess = FindExistingTargetFiles(environment.Host.FileSystem, action.Args, outputBasePath);
}
if (!projectsToProcess.Any())
{
// no projects found. Error.
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_UnresolvedProjFile);
return false;
}
bool success = true;
foreach (string projectFile in projectsToProcess)
{
success &= AddReference(action, projectFile, outputBasePath, creationEffects);
if (!success)
{
return false;
}
}
return true;
}
private static IReadOnlyList<string> TryFindProjects(IEngineEnvironmentSettings environment, string outputBasePath, HashSet<string> extensionLimiters)
{
try
{
return FindProjFileAtOrAbovePath(environment.Host.FileSystem, outputBasePath, extensionLimiters);
}
catch (DirectoryNotFoundException)
{
return [];
}
}
private static IReadOnlyList<string> FindExistingTargetFiles(IPhysicalFileSystem fileSystem, IReadOnlyDictionary<string, string> actionArgs, string outputBasePath)
{
var targetFiles = GetTargetFilesPaths(actionArgs, outputBasePath);
var foundFiles = targetFiles?
.Where(fileSystem.FileExists)
.ToList();
return foundFiles ?? [];
}
private bool AddReference(IPostAction actionConfig, string projectFile, string outputBasePath, ICreationEffects creationEffects)
{
if (actionConfig.Args == null || !actionConfig.Args.TryGetValue("reference", out string? referenceToAdd))
{
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ActionMisconfigured);
return false;
}
if (!actionConfig.Args.TryGetValue("referenceType", out string? referenceType))
{
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Error_ActionMisconfigured);
return false;
}
if (string.Equals(referenceType, "project", StringComparison.OrdinalIgnoreCase))
{
// replace the referenced project file's name in case it has been renamed
string? referenceNameChange = GetTargetForSource((ICreationEffects2)creationEffects, referenceToAdd, outputBasePath).SingleOrDefault();
string relativeProjectReference = referenceNameChange ?? referenceToAdd;
referenceToAdd = Path.GetFullPath(relativeProjectReference, outputBasePath);
return AddProjectReference(projectFile, referenceToAdd);
}
else if (string.Equals(referenceType, "package", StringComparison.OrdinalIgnoreCase))
{
actionConfig.Args.TryGetValue("version", out string? version);
return AddPackageReference(projectFile, referenceToAdd, version);
}
else if (string.Equals(referenceType, "framework", StringComparison.OrdinalIgnoreCase))
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_Error_FrameworkNotSupported, referenceToAdd));
return false;
}
else
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_Error_UnsupportedRefType, referenceType));
return false;
}
}
private bool AddPackageReference(string projectPath, string packageName, string? version)
{
try
{
if (string.IsNullOrWhiteSpace(version))
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_AddPackageReference, packageName, projectPath));
}
else
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_AddPackageReference_WithVersion, packageName, version, projectPath));
}
bool succeeded = _addPackageReferenceCallback(projectPath, packageName, version);
if (succeeded)
{
Reporter.Output.WriteLine(LocalizableStrings.PostAction_AddReference_Succeeded);
}
else
{
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Failed);
}
return succeeded;
}
catch (Exception e)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_AddPackageReference_Failed, e.Message));
return false;
}
}
private bool AddProjectReference(string projectPath, string projectToAdd)
{
try
{
Reporter.Output.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_AddProjectReference, projectToAdd, projectPath));
bool succeeded = _addProjectReferenceCallback(projectPath, projectToAdd);
if (succeeded)
{
Reporter.Output.WriteLine(LocalizableStrings.PostAction_AddReference_Succeeded);
}
else
{
Reporter.Error.WriteLine(LocalizableStrings.PostAction_AddReference_Failed);
}
return succeeded;
}
catch (Exception e)
{
Reporter.Error.WriteLine(string.Format(LocalizableStrings.PostAction_AddReference_AddProjectReference_Failed, e.Message));
return false;
}
}
}