-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHost.cs
673 lines (628 loc) · 25.2 KB
/
Host.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
// ReSharper disable RedundantUsingDirective
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable CheckNamespace
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq.Expressions;
using System.Text;
using CSharpInteractive;
using CSharpInteractive.Core;
using HostApi;
using NuGet.Versioning;
// ReSharper disable HeapView.PossibleBoxingAllocation
/// <summary>
/// API host.
/// </summary>
[ExcludeFromCodeCoverage]
[SuppressMessage("Design", "CA1050:Declare types in namespaces")]
#if APPLICATION
public static class Host
#else
public static class Components
#endif
{
private static readonly Root Root = Composition.Shared.Root;
private static readonly IHost CurHost = Root.Host;
#if APPLICATION
private static readonly IDisposable FinishToken;
static Host()
{
if (AppDomain.CurrentDomain.GetAssemblies().Any(i => string.Equals("dotnet-csi", i.GetName().Name, StringComparison.InvariantCultureIgnoreCase)))
{
FinishToken = Disposable.Empty;
return;
}
Root.Info.ShowHeader();
FinishToken = Disposable.Create(Root.ExitTracker.Track(), Root.StatisticsRegistry.Start());
AppDomain.CurrentDomain.ProcessExit += OnCurrentDomainOnProcessExit;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
}
private static void OnCurrentDomainOnProcessExit(object? o, EventArgs eventArgs) =>
Finish();
internal static void Finish()
{
try
{
FinishToken.Dispose();
Composition.Shared.Dispose();
}
catch (Exception ex)
{
try
{
Root.Log.Error(ErrorId.Unhandled, ex);
}
catch (Exception)
{
// ignored
}
}
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
if (e.ExceptionObject is Exception error)
{
Root.Log.Error(ErrorId.Exception, error);
}
else
{
Root.Log.Error(ErrorId.Exception, [new Text(e.ExceptionObject.ToString() ?? "Unhandled exception.", Color.Error)]);
}
Root.ExitTracker.Exit(1);
}
catch
{
// ignored
}
}
#endif
/// <summary>
/// List of command line arguments.
/// <example>
/// <code>
/// Info("First argument: " + (Args.Count > 0 ? Args[0] : "empty"));
/// </code>
/// </example>
/// </summary>
public static IReadOnlyList<string> Args => CurHost.Args;
/// <summary>
/// Set of properties.
/// <example>
/// <code>
/// Info("Version: " + Props.Get("version", "1.0.0"));
/// Props["version"] = "1.0.1";
/// </code>
/// </example>
/// </summary>
/// <seealso cref="IProperties.TryGetValue"/>
/// <seealso cref="IProperties.this"/>
public static IProperties Props => CurHost.Props;
/// <summary>
/// Writes an empty line to stdOut.
/// <example>
/// <code>
/// WriteLine("Hello");
/// </code>
/// </example>
/// </summary>
public static void WriteLine() => CurHost.WriteLine();
/// <summary>
/// Writes a line to stdOut.
/// <example>
/// <code>
/// WriteLine("Hello !");
/// WriteLine("Hello !!!", Color.Highlighted);
/// </code>
/// </example>
/// </summary>
/// <param name="line">Any value that will be converted to a line.</param>
/// <param name="color">Line color, optional.</param>
/// <typeparam name="T">The type of the value to be converted to a line.</typeparam>
public static void WriteLine<T>(T line, Color color = Color.Default) => CurHost.WriteLine(line, color);
/// <summary>
/// Writes a line to stdOut.
/// <example>
/// <code>
/// WriteLine("Hello !".WithColor(Color.Highlighted));
/// </code>
/// </example>
/// </summary>
/// <param name="line">Any value that will be converted to a line.</param>
public static void WriteLine(params Text[] line) => CurHost.WriteLine(line);
/// <summary>
/// Writes an error to stdErr. This error will affect the summary run statistics.
/// <example>
/// <code>
/// Error("Error details");
/// Error("Error details", "ERR327");
/// </code>
/// </example>
/// </summary>
/// <param name="error">Error message.</param>
/// <param name="errorId">Unique error identifier, optional.</param>
public static void Error(string? error, string? errorId = null) => CurHost.Error(error, errorId);
/// <summary>
/// Writes an error to stdErr. This error will affect the summary run statistics.
/// <example>
/// <code>
/// Error(new Text("Some "), new Text("error", Color.Error));
/// </code>
/// </example>
/// </summary>
/// <param name="error">Error message.</param>
public static void Error(params Text[] error) => CurHost.Error(error);
/// <summary>
/// Writes an error to stdErr. This error will affect the summary run statistics.
/// <example>
/// <code>
/// Error("ERR327", new Text("Some "), new Text("error", Color.Error));
/// </code>
/// </example>
/// </summary>
/// <param name="errorId">Unique error identifier, optional.</param>
/// <param name="error">Error message.</param>
public static void Error(string errorId, params Text[] error) => CurHost.Error(errorId, error);
/// <summary>
/// Writes a warning to stdOut. This warning will affect the summary run statistics.
/// <example>
/// <code>
/// Warning("Warning");
/// </code>
/// </example>
/// </summary>
/// <param name="warning">Warning message.</param>
public static void Warning(string? warning) => CurHost.Warning(warning);
/// <summary>
/// Writes a warning to stdOut. This warning will affect the summary run statistics.
/// <example>
/// <code>
/// Warning(new Text("Some "), new Text("warning", Color.Warning));
/// </code>
/// </example>
/// </summary>
/// <param name="warning">Warning message.</param>
public static void Warning(params Text[] warning) => CurHost.Warning(warning);
/// <summary>
/// Writes a summary message to stdOut.
/// <example>
/// <code>
/// Info("Some info");
/// </code>
/// </example>
/// </summary>
/// <param name="summary">Summary message.</param>
public static void Summary(string? summary) => CurHost.Summary(summary);
/// <summary>
/// Writes a summary message to stdOut.
/// <example>
/// <code>
/// Summary(new Text("Some "), new Text("summary", Color.Highlighted));
/// </code>
/// </example>
/// </summary>
/// <param name="summary">Summary message.</param>
public static void Summary(params Text[] summary) => CurHost.Summary(summary);
/// <summary>
/// Writes an information message to stdOut.
/// <example>
/// <code>
/// Info("Some info");
/// </code>
/// </example>
/// </summary>
/// <param name="text">Information message.</param>
public static void Info(string? text) => CurHost.Info(text);
/// <summary>
/// Writes an information message to stdOut.
/// <example>
/// <code>
/// Ingo(new Text("Some "), new Text("info", Color.Highlighted));
/// </code>
/// </example>
/// </summary>
/// <param name="text">Information message.</param>
public static void Info(params Text[] text) => CurHost.Info(text);
/// <summary>
/// Writes a trace message to stdOut for the appropriate logging level.
/// <example>
/// <code>
/// Trace("Trace message");
/// </code>
/// </example>
/// <example>
/// When run as a script:
/// <code>
/// #l Diagnostic
/// Trace("Tracing details.");
/// </code>
/// </example>
/// </summary>
/// <param name="trace">Trace message.</param>
/// <param name="origin">Source of the trace message, optional.</param>
public static void Trace(string? trace, string? origin = null) => CurHost.Trace(trace, origin);
/// <summary>
/// Writes a trace message to stdOut for the appropriate logging level.
/// <example>
/// <code>
/// Trace(new Text("Trace message", Color.Details));
/// </code>
/// </example>
/// <example>
/// When run as a script:
/// <code>
/// #l Diagnostic
/// Trace("Tracing ", "details".WithColor(Color.Details));
/// </code>
/// </example>
/// </summary>
/// <param name="trace">Trace message.</param>
public static void Trace(Text[] trace) => CurHost.Trace(trace);
/// <summary>
/// Provides an instance of a service by its type.
/// <example>
/// <code>
/// var nuget = GetService<INuGet>();
/// </code>
/// </example>
/// </summary>
/// <typeparam name="T">Type of service.</typeparam>
/// <returns>Service instance.</returns>
/// <seealso cref="IHost"/>
/// <seealso cref="ICommandLineRunner"/>
/// <seealso cref="IBuildRunner"/>
/// <seealso cref="INuGet"/>
/// <seealso cref="IServiceProvider"/>
[Pure]
// ReSharper disable once UnusedMethodReturnValue.Global
public static T GetService<T>() => CurHost.GetService<T>();
/// <summary>
/// Runs a command line.
/// <example>
/// <code>
/// new CommandLine("whoami").Run();
/// </code>
/// </example>
/// </summary>
/// <param name="commandLine">Command line to run.</param>
/// <param name="handler">Event handler for running command line events, optional.</param>
/// <param name="timeout">Time to wait for command line running to complete, optional. By default, waits for the end of running without limit. If the value is exceeded, the command line process and its children will be cancelled.</param>
/// <returns>The result of a command line running.</returns>
/// <seealso cref="RunAsync"/>
/// <seealso cref="Output"/>
public static ICommandLineResult Run(
this ICommandLine commandLine,
Action<Output>? handler = null,
TimeSpan timeout = default)
{
ArgumentNullException.ThrowIfNull(commandLine);
return Root.CommandLineRunner.Value.Run(commandLine, handler, timeout);
}
/// <summary>
/// Runs a command line in asynchronous way.
/// <example>
/// <code>
/// await new CommandLine("whoami").RunAsync();
/// </code>
/// </example>
/// </summary>
/// <param name="commandLine">Command line to run.</param>
/// <param name="handler">Event handler for running command line events, optional.</param>
/// <param name="cancellationToken">Propagates notification that a running should be canceled, optional.</param>
/// <returns>The result of an asynchronous command line running.</returns>
/// <seealso cref="Run"/>
/// <seealso cref="Task{T}"/>
/// <seealso cref="Output"/>
/// <seealso cref="CancellationToken"/>
public static Task<ICommandLineResult> RunAsync(
this ICommandLine commandLine,
Action<Output>? handler = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(commandLine);
return Root.CommandLineRunner.Value.RunAsync(commandLine, handler, cancellationToken);
}
/// <summary>
/// Runs a build.
/// <example>
/// <code>
/// new DotNetBuild().Build();
/// </code>
/// </example>
/// </summary>
/// <param name="commandLine">Command line to build.</param>
/// <param name="handler">Event handler for build events, optional.</param>
/// <param name="timeout">Time to wait for build running to complete, optional. By default, waits for the end of build running without limit. If the value is exceeded, the command line process and its children will be cancelled.</param>
/// <returns>Result of building with the command line.</returns>
/// <seealso cref="BuildAsync"/>
/// <seealso cref="BuildMessage"/>
public static IBuildResult Build(
this ICommandLine commandLine,
Action<BuildMessage>? handler = null,
TimeSpan timeout = default)
{
ArgumentNullException.ThrowIfNull(commandLine);
return Root.BuildRunner.Value.Build(commandLine, handler, timeout);
}
/// <summary>
/// Runs a build in asynchronous way.
/// <example>
/// <code>
/// await new DotNetBuild().BuildAsync();
/// </code>
/// </example>
/// </summary>
/// <param name="commandLine">Command line to build.</param>
/// <param name="handler">Event handler for build events.</param>
/// <param name="cancellationToken">Propagates notification that a running of a build should be canceled, optional.</param>
/// <returns>Asynchronous build result using the command line.</returns>
/// <seealso cref="Build"/>
/// <seealso cref="Task{T}"/>
/// <seealso cref="BuildMessage"/>
/// <seealso cref="CancellationToken"/>
public static Task<IBuildResult> BuildAsync(
this ICommandLine commandLine,
Action<BuildMessage>? handler = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(commandLine);
return Root.BuildRunner.Value.BuildAsync(commandLine, handler, cancellationToken);
}
/// <summary>
/// Ensures that the command line or build was completed successfully.
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.Run"/>
/// <seealso cref="IBuildRunner.Build"/>
public static IEnumerable<TResult> EnsureSuccess<TResult>(
this IEnumerable<TResult> result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess<IEnumerable<TResult>, TResult>(result, isSuccess, failureExitCode);
}
/// <summary>
/// Ensures that the command line or build was completed successfully in asynchronous way.
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.RunAsync"/>
/// <seealso cref="IBuildRunner.BuildAsync"/>
/// <seealso cref="Task{T}"/>
public static async Task<IEnumerable<TResult>> EnsureSuccess<TResult>(
this Task<IEnumerable<TResult>> result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess<IEnumerable<TResult>, TResult>(await result, isSuccess, failureExitCode);
}
/// <summary>
/// Ensures that the command line or build was completed successfully.
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.Run"/>
/// <seealso cref="IBuildRunner.Build"/>
public static TResult[] EnsureSuccess<TResult>(
this TResult[] result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess<TResult[], TResult>(result, isSuccess, failureExitCode);
}
/// <summary>
/// Ensures that the command line or build was completed successfully.
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.RunAsync"/>
/// <seealso cref="IBuildRunner.BuildAsync"/>
/// <seealso cref="Task{T}"/>
public static async Task<TResult[]> EnsureSuccess<TResult>(
this Task<TResult[]> result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess<TResult[], TResult>(await result, isSuccess, failureExitCode);
}
/// <summary>
/// Ensures that the command line or build was completed successfully.
/// <example>
/// <code>
/// new DotNetBuild()
/// .Build()
/// .EnsureSuccess();
/// </code>
/// </example>
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.Run"/>
/// <seealso cref="IBuildRunner.Build"/>
public static TResult EnsureSuccess<TResult>(
this TResult result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess([result], isSuccess, failureExitCode).First();
}
/// <summary>
/// Ensures that the command line or build was completed successfully.
/// <example>
/// <code>
/// await new DotNetBuild()
/// .BuildAsync()
/// .EnsureSuccess();
/// </code>
/// </example>
/// </summary>
/// <param name="result">Enumeration of results to be verified.</param>
/// <param name="isSuccess">Function to check the result for success, optional. Returns True if successful, False if not successful and empty if warning.</param>
/// <param name="failureExitCode">If unsuccessful, terminates with the specified exit code, which is optional and defaults to 1.</param>
/// <typeparam name="TResult">Result type. Should implement the <see cref="ICommandLineResult"/> interface.</typeparam>
/// <returns>Simply returns the passed result, for possible later use in a call chain.</returns>
/// <seealso cref="ICommandLineResult"/>
/// <seealso cref="IBuildResult"/>
/// <seealso cref="ICommandLineRunner.RunAsync"/>
/// <seealso cref="IBuildRunner.BuildAsync"/>
/// <seealso cref="Task{T}"/>
public static async Task<TResult> EnsureSuccess<TResult>(
this Task<TResult> result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
return EnsureSuccess(await result, isSuccess, failureExitCode);
}
/// <summary>
/// Tries to get a property by its key.
/// <example>
/// <code>
/// if (Props.TryGet("configuration", out configuration))
/// {
/// // do something
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="properties">A set of properties of type <see cref="IProperties"/>.</param>
/// <param name="key">Property key.</param>
/// <param name="value">The resulting property converted to type <typeparamref name="T"/>.</param>
/// <typeparam name="T">Property type.</typeparam>
/// <returns><c>True</c> if the property is obtained successfully, otherwise <c>False</c>.</returns>
/// <seealso cref="IProperties"/>
/// <seealso cref="IProperties.TryGetValue"/>
/// <seealso cref="IProperties.get_Item"/>
public static bool TryGet<T>(
this IProperties properties,
string key,
[MaybeNullWhen(false)] out T value)
{
ArgumentNullException.ThrowIfNull(properties);
ArgumentNullException.ThrowIfNull(key);
if (properties.TryGetValue(key, out var valStr))
{
if (typeof(T) == typeof(string))
{
value = (T)(object)valStr;
return true;
}
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter.CanConvertFrom(typeof(string)))
{
var nullableValue = converter.ConvertFrom(valStr);
if (!Equals(nullableValue, null))
{
try
{
value = (T)nullableValue;
return true;
}
catch (InvalidCastException)
{ }
}
}
}
value = default;
return false;
}
/// <summary>
/// Gets a property by its key if it is defined and convertible to type <typeparamref name="T"/>, or returns a default value.
/// <example>
/// <code>
/// var configuration = Props.Get("configuration", "Release");
/// </code>
/// </example>
/// </summary>
/// <param name="properties">A set of properties of type <see cref="IProperties"/></param>
/// <param name="key">Property key.</param>
/// <param name="defaultValue">Default value.</param>
/// <typeparam name="T">Property type.</typeparam>
/// <returns>The resulting property converted to type <typeparamref name="T"/>.</returns>
/// <seealso cref="IProperties"/>
/// <seealso cref="IProperties.TryGetValue"/>
/// <seealso cref="IProperties.get_Item"/>
public static T Get<T>(
this IProperties properties,
string key,
T defaultValue)
{
ArgumentNullException.ThrowIfNull(properties);
ArgumentNullException.ThrowIfNull(key);
return properties.TryGet<T>(key, out var value)
? value
: defaultValue;
}
private static T EnsureSuccess<T, TResult>(
T result,
Func<TResult, bool?>? isSuccess = null,
int? failureExitCode = 1)
where T: IEnumerable<TResult>
where TResult: ICommandLineResult
{
ArgumentNullException.ThrowIfNull(result);
isSuccess ??= r => r is ISuccessDeterminant successDeterminant ? successDeterminant.IsSuccess : true;
var hasError = false;
foreach (var nextResult in result)
{
switch (isSuccess(nextResult))
{
case true:
break;
case null:
Root.Log.Warning($"{nextResult}.");
break;
case false:
hasError = true;
Root.Log.Error(ErrorId.Build, $"{nextResult}.");
break;
}
}
if (hasError && failureExitCode is { } exitCode)
{
Root.ExitTracker.Exit(exitCode);
}
return result;
}
}