-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathDotnetHelpers.cs
349 lines (317 loc) · 14.7 KB
/
DotnetHelpers.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Azure.Functions.Cli.Common;
using Azure.Functions.Cli.Exceptions;
using Colors.Net;
using Microsoft.Azure.WebJobs.Extensions.Http;
using static Azure.Functions.Cli.Common.OutputTheme;
namespace Azure.Functions.Cli.Helpers
{
public static class DotnetHelpers
{
private const string WebJobsTemplateBasePackId = "Microsoft.Azure.WebJobs";
private const string IsolatedTemplateBasePackId = "Microsoft.Azure.Functions.Worker";
public static void EnsureDotnet()
{
if (!CommandChecker.CommandExists("dotnet"))
{
throw new CliException("dotnet sdk is required for dotnet based functions. Please install https://microsoft.com/net");
}
}
/// <summary>
/// Function that determines TargetFramework of a project even when it's defined outside of the .csproj file,
/// e.g. in Directory.Build.props
/// </summary>
/// <param name="projectDirectory">Directory containing the .csproj file</param>
/// <param name="projectFilename">Name of the .csproj file</param>
/// <returns>Target framework, e.g. net8.0</returns>
/// <exception cref="CliException"></exception>
public static async Task<string> DetermineTargetFramework(string projectDirectory, string projectFilename = null)
{
EnsureDotnet();
if (projectFilename == null)
{
var projectFilePath = ProjectHelpers.FindProjectFile(projectDirectory);
if (projectFilePath != null)
{
projectFilename = Path.GetFileName(projectFilePath);
}
}
var exe = new Executable(
"dotnet",
$"build {projectFilename} -getproperty:TargetFramework",
workingDirectory: projectDirectory,
environmentVariables: new Dictionary<string, string>
{
// https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-environment-variables
["DOTNET_NOLOGO"] = "1", // do not write disclaimer to stdout
["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1", // just in case
});
StringBuilder output = new();
var exitCode = await exe.RunAsync(o => output.Append(o), e => ColoredConsole.Error.WriteLine(ErrorColor(e)));
if (exitCode != 0)
{
throw new CliException($"Can not determine target framework for dotnet project at ${projectDirectory}");
}
return output.ToString();
}
public static async Task DeployDotnetProject(string Name, bool force, WorkerRuntime workerRuntime, string targetFramework = "")
{
await TemplateOperation(async () =>
{
var frameworkString = string.IsNullOrEmpty(targetFramework)
? string.Empty
: $"--Framework \"{targetFramework}\"";
var connectionString = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? $"--StorageConnectionStringValue \"{Constants.StorageEmulatorConnectionString}\""
: string.Empty;
var exe = new Executable("dotnet", $"new func {frameworkString} --AzureFunctionsVersion v4 --name {Name} {connectionString} {(force ? "--force" : string.Empty)}");
var exitCode = await exe.RunAsync(o => { }, e => ColoredConsole.Error.WriteLine(ErrorColor(e)));
if (exitCode != 0)
{
throw new CliException("Error creating project template");
}
}, workerRuntime);
}
public static async Task DeployDotnetFunction(string templateName, string functionName, string namespaceStr, string language, WorkerRuntime workerRuntime, AuthorizationLevel? httpAuthorizationLevel = null)
{
ColoredConsole.WriteLine($"{Environment.NewLine}Creating dotnet function...");
await TemplateOperation(async () =>
{
// In .NET 6.0, the 'dotnet new' command requires the short name.
string templateShortName = GetTemplateShortName(templateName);
string exeCommandArguments = $"new {templateShortName} --name {functionName} --namespace {namespaceStr} --language {language}";
if (httpAuthorizationLevel != null)
{
if (templateName.Equals(Constants.HttpTriggerTemplateName, StringComparison.OrdinalIgnoreCase))
{
exeCommandArguments += $" --AccessRights {httpAuthorizationLevel}";
}
else
{
throw new CliException(Constants.AuthLevelErrorMessage);
}
}
var exe = new Executable("dotnet", exeCommandArguments);
string dotnetNewErrorMessage = string.Empty;
var exitCode = await exe.RunAsync(o => { }, e => {
dotnetNewErrorMessage = string.Concat(dotnetNewErrorMessage, Environment.NewLine, e);
});
if (exitCode != 0)
{
// Only print the error message from dotnet new command when command was not successful to avoid confusing people.
if (!string.IsNullOrWhiteSpace(dotnetNewErrorMessage))
{
ColoredConsole.Error.WriteLine(ErrorColor(dotnetNewErrorMessage));
}
throw new CliException("Error creating function.");
}
}, workerRuntime);
}
private static string GetTemplateShortName(string templateName) => templateName.ToLowerInvariant() switch
{
"blobtrigger" => "blob",
"eventgridblobtrigger" => "eventgridblob",
"cosmosdbtrigger" => "cosmos",
"durablefunctionsorchestration" => "durable",
"eventgridtrigger" => "eventgrid",
"eventgridcloudeventtrigger" => "eventgridcloudevent",
"eventhubtrigger" => "eventhub",
"httptrigger" => "http",
"iothubtrigger" => "iothub",
"kafkatrigger" => "kafka",
"kafkaoutput" => "kafkao",
"queuetrigger" => "queue",
"sendgrid" => "sendgrid",
"servicebusqueuetrigger" => "squeue",
"servicebustopictrigger" => "stopic",
"timertrigger" => "timer",
"daprpublishoutputbinding" => "daprPublishOutputBinding",
"daprserviceinvocationtrigger" => "daprServiceInvocationTrigger",
"daprtopictrigger" => "daprTopicTrigger",
_ => throw new CsTemplateNotFoundException(templateName)
};
internal static IEnumerable<string> GetTemplates(WorkerRuntime workerRuntime)
{
if (workerRuntime == WorkerRuntime.dotnetIsolated)
{
return new[]
{
"QueueTrigger",
"HttpTrigger",
"BlobTrigger",
"EventGridBlobTrigger",
"TimerTrigger",
"EventHubTrigger",
"ServiceBusQueueTrigger",
"ServiceBusTopicTrigger",
"EventGridTrigger",
"CosmosDBTrigger",
"DaprPublishOutputBinding",
"DaprServiceInvocationTrigger",
"DaprTopicTrigger",
};
}
return new[]
{
"QueueTrigger",
"HttpTrigger",
"BlobTrigger",
"TimerTrigger",
"KafkaTrigger",
"KafkaOutput",
"DurableFunctionsOrchestration",
"SendGrid",
"EventHubTrigger",
"ServiceBusQueueTrigger",
"ServiceBusTopicTrigger",
"EventGridTrigger",
"EventGridCloudEventTrigger",
"CosmosDBTrigger",
"IotHubTrigger",
"DaprPublishOutputBinding",
"DaprServiceInvocationTrigger",
"DaprTopicTrigger",
};
}
public static bool CanDotnetBuild()
{
EnsureDotnet();
// dotnet build will only search for .csproj files within the current directory (when no .csproj file is passed), so we limit our search to that directory only
var csProjFiles = FileSystemHelpers.GetFiles(Environment.CurrentDirectory, searchPattern: "*.csproj", searchOption: SearchOption.TopDirectoryOnly).ToList();
var fsProjFiles = FileSystemHelpers.GetFiles(Environment.CurrentDirectory, searchPattern: "*.fsproj", searchOption: SearchOption.TopDirectoryOnly).ToList();
// If the project name is extensions only then is extensions.csproj a valid csproj file
if (!Path.GetFileName(Environment.CurrentDirectory).Equals("extensions"))
{
csProjFiles.Remove("extensions.csproj");
fsProjFiles.Remove("extensions.fsproj");
}
if (csProjFiles.Count + fsProjFiles.Count > 1)
{
throw new CliException($"Can't determine Project to build. Expected 1 .csproj or .fsproj but found {csProjFiles.Count + fsProjFiles.Count}");
}
return csProjFiles.Count + fsProjFiles.Count == 1;
}
public static async Task BuildAndChangeDirectory(string outputPath, string cliParams)
{
if (CanDotnetBuild())
{
await BuildDotnetProject(outputPath, cliParams);
Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, outputPath);
}
else if (StaticSettings.IsDebug)
{
ColoredConsole.WriteLine("Could not find a valid .csproj file. Skipping the build.");
}
}
public static async Task<bool> BuildDotnetProject(string outputPath, string dotnetCliParams, bool showOutput = true)
{
if (FileSystemHelpers.DirectoryExists(outputPath))
{
FileSystemHelpers.DeleteDirectorySafe(outputPath);
}
var exe = new Executable("dotnet", $"build --output {outputPath} {dotnetCliParams}");
var exitCode = showOutput
? await exe.RunAsync(o => ColoredConsole.WriteLine(o), e => ColoredConsole.Error.WriteLine(e))
: await exe.RunAsync();
if (exitCode != 0)
{
throw new CliException("Error building project");
}
return true;
}
public static string GetCsprojOrFsproj()
{
EnsureDotnet();
var csProjFiles = FileSystemHelpers.GetFiles(Environment.CurrentDirectory, searchPattern: "*.csproj", excludedDirectories: ["obj"]).ToList();
if (csProjFiles.Count == 1)
{
return csProjFiles.First();
}
else
{
var fsProjFiles = FileSystemHelpers.GetFiles(Environment.CurrentDirectory, searchPattern: "*.fsproj", excludedDirectories: ["obj"]).ToList();
if (fsProjFiles.Count == 1)
{
return fsProjFiles.First();
}
else
{
throw new CliException($"Can't determine Project to build. Expected 1 .csproj or .fsproj but found {csProjFiles.Count + fsProjFiles.Count}");
}
}
}
private static Task TemplateOperation(Func<Task> action, WorkerRuntime workerRuntime)
{
EnsureDotnet();
if (workerRuntime == WorkerRuntime.dotnetIsolated)
{
return IsolatedTemplateOperation(action);
}
else
{
return WebJobsTemplateOperation(action);
}
}
private static async Task IsolatedTemplateOperation(Func<Task> action)
{
try
{
await UninstallWebJobsTemplates();
await InstallIsolatedTemplates();
await action();
}
finally
{
await UninstallIsolatedTemplates();
}
}
private static async Task WebJobsTemplateOperation(Func<Task> action)
{
try
{
await UninstallIsolatedTemplates();
await InstallWebJobsTemplates();
await action();
}
finally
{
await UninstallWebJobsTemplates();
}
}
private static async Task UninstallIsolatedTemplates()
{
string projTemplates = $"{IsolatedTemplateBasePackId}.ProjectTemplates";
string itemTemplates = $"{IsolatedTemplateBasePackId}.ItemTemplates";
var exe = new Executable("dotnet", $"new -u \"{projTemplates}\"");
await exe.RunAsync();
exe = new Executable("dotnet", $"new -u \"{itemTemplates}\"");
await exe.RunAsync();
}
private static async Task UninstallWebJobsTemplates()
{
string projTemplates = $"{WebJobsTemplateBasePackId}.ProjectTemplates";
string itemTemplates = $"{WebJobsTemplateBasePackId}.ItemTemplates";
var exe = new Executable("dotnet", $"new -u \"{projTemplates}\"");
await exe.RunAsync();
exe = new Executable("dotnet", $"new -u \"{itemTemplates}\"");
await exe.RunAsync();
}
private static Task InstallWebJobsTemplates() => DotnetTemplatesAction("install", "templates");
private static Task InstallIsolatedTemplates() => DotnetTemplatesAction("install", Path.Combine("templates", $"net-isolated"));
private static async Task DotnetTemplatesAction(string action, string templateDirectory)
{
var templatesLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), templateDirectory);
if (!FileSystemHelpers.DirectoryExists(templatesLocation))
{
throw new CliException($"Can't find templates location. Looked under '{templatesLocation}'");
}
foreach (var nupkg in Directory.GetFiles(templatesLocation, "*.nupkg", SearchOption.TopDirectoryOnly))
{
var exe = new Executable("dotnet", $"new --{action} \"{nupkg}\"");
await exe.RunAsync();
}
}
}
}