-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathTransformBase.cs
More file actions
931 lines (803 loc) · 36 KB
/
TransformBase.cs
File metadata and controls
931 lines (803 loc) · 36 KB
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Management.Automation.Language;
using System.Text;
using Markdig.Helpers;
using Microsoft.PowerShell.PlatyPS.Model;
namespace Microsoft.PowerShell.PlatyPS
{
internal abstract class TransformBase
{
protected readonly TransformSettings Settings;
public TransformBase(TransformSettings settings) => Settings = settings;
internal abstract Collection<CommandHelp> Transform(string[] source);
protected CommandHelp ConvertCmdletInfo(CommandInfo? commandInfo)
{
if (commandInfo is null)
{
throw new ArgumentNullException();
}
string cmdName = commandInfo is ExternalScriptInfo ? commandInfo.Source : commandInfo.Name;
Collection<PSObject> help = PowerShellAPI.GetHelpForCmdlet(cmdName, Settings.Session);
bool addDefaultStrings = false;
dynamic? helpItem = null;
if (help.Count == 1)
{
helpItem = help[0];
// If the description and examples are empty the help is auto-generated.
// So assume that no existing help content is available.
if (string.IsNullOrEmpty(GetStringFromDescriptionArray(helpItem.description)) &&
string.IsNullOrEmpty(helpItem.examples))
{
addDefaultStrings = true;
}
}
else
{
addDefaultStrings = true;
}
CommandHelp cmdHelp = new(commandInfo.Name, commandInfo.ModuleName, Settings.Locale);
cmdHelp.Metadata = MetadataUtils.GetCommandHelpBaseMetadataFromCommandInfo(commandInfo);
cmdHelp.ExternalHelpFile = cmdHelp.Metadata["external help file"].ToString() ?? string.Empty;
cmdHelp.OnlineVersionUrl = Settings.OnlineVersionUrl ?? cmdHelp.Metadata["HelpUri"] as string;
cmdHelp.SchemaVersion = cmdHelp.Metadata["PlatyPS schema version"] as string ?? string.Empty;
cmdHelp.Synopsis = GetSynopsis(helpItem, addDefaultStrings);
cmdHelp.AddSyntaxItemRange(GetSyntaxItem(commandInfo, helpItem));
cmdHelp.Description = GetDescription(helpItem, addDefaultStrings).Trim();
cmdHelp.AddExampleItemRange(GetExamples(helpItem, addDefaultStrings));
var parameters = GetParameters(commandInfo, helpItem, addDefaultStrings);
cmdHelp.AddParameterRange(parameters);
cmdHelp.HasCmdletBinding = (commandInfo is FunctionInfo funcInfo && funcInfo.CmdletBinding) ||
commandInfo is CmdletInfo ||
(commandInfo is ExternalScriptInfo extInfo && extInfo.ScriptBlock.Attributes.Contains(new CmdletBindingAttribute()));
if (!string.IsNullOrEmpty(cmdHelp.ModuleName))
{
var moduleInfos = PowerShellAPI.GetModuleInfo(cmdHelp.ModuleName, Settings.Session);
if (moduleInfos?.Count > 0)
{
cmdHelp.ModuleGuid = moduleInfos[0].Guid;
}
}
foreach(var input in GetInputInfo(commandInfo, helpItem, addDefaultStrings))
{
cmdHelp.AddInputItem(input);
}
foreach(var output in GetOutputInfo(commandInfo, helpItem, addDefaultStrings))
{
cmdHelp.AddOutputItem(output);
}
cmdHelp.Notes = GetNotes(helpItem, addDefaultStrings);
cmdHelp.AddRelatedLinksRange(GetRelatedLinks(helpItem));
return cmdHelp;
}
// We don't want to return any arrays, so trim the last "[]" if it is found;
// We can also simplify the string if desired.
private string GetAdjustedTypename(Type t, bool simplify = false)
{
var t2 = Nullable.GetUnderlyingType(t) ?? t;
string tName = simplify ? LanguagePrimitives.ConvertTo<string>(t2) : t2.FullName;
return tName;
}
// We need to inspect both the help and the parameters for those that take pipeline input.
private List<InputOutput> GetInputInfo(CommandInfo commandInfo, dynamic? helpItem, bool addDefaultStrings)
{
IEnumerable<ParameterMetadata> parameters;
// It is possible that the Parameters member is null, so protect against that.
if (commandInfo.Parameters is null)
{
parameters = new List<ParameterMetadata>();
}
else
{
parameters = commandInfo.Parameters.Values;
}
List<InputOutput> inputList = new();
HashSet<string> inputTypeNames = new();
// Sometime the help content does not have any input type
if (helpItem?.inputTypes?.inputType is not null)
{
List<InputOutput> ioItems = GetInputOutputItemsFromHelp(helpItem.inputTypes.inputType);
foreach(var ioItem in ioItems)
{
if (! inputTypeNames.Contains(ioItem.Typename))
{
inputList.Add(ioItem);
inputTypeNames.Add(ioItem.Typename);
}
}
}
// Check the parameters for ValueFromPipeline or ValueFromPipelineByPropertyName
foreach(var parameter in parameters)
{
string parameterType = GetAdjustedTypename(parameter.ParameterType);
foreach(var pSet in parameter.ParameterSets)
{
if (pSet.Value.ValueFromPipeline || pSet.Value.ValueFromPipelineByPropertyName)
{
if (! inputTypeNames.Contains(parameterType))
{
inputList.Add(new InputOutput(parameterType, Constants.FillInDescription));
inputTypeNames.Add(parameterType);
}
}
}
}
return inputList;
}
private List<InputOutput> GetOutputInfo(CommandInfo commandInfo, dynamic? helpItem, bool addDefaultStrings)
{
List<InputOutput> outputList = new();
HashSet<string> outputTypeNames = new();
// Sometime the help content does not have any output type
if (helpItem?.returnValues?.returnValue is not null)
{
List<InputOutput> outputItems = GetInputOutputItemsFromHelp(helpItem.returnValues.returnValue);
foreach(var o in outputItems)
{
if (! outputTypeNames.Contains(o.Typename))
{
outputList.Add(o);
outputTypeNames.Add(o.Typename);
}
}
}
// Check for the output on the CommandInfo object
foreach(var outputType in commandInfo.OutputType) {
string outputName = outputType.Name;
if (outputName.EndsWith("[]"))
{
outputName = FixUpTypeName(outputName);
}
if (!outputTypeNames.Contains(outputName))
{
outputList.Add(new InputOutput(outputName, Constants.FillInDescription));
outputTypeNames.Add(outputName);
}
}
return outputList;
}
protected IEnumerable<Parameter> GetParameters(CommandInfo cmdletInfo, dynamic? helpItem, bool addDefaultString)
{
List<Parameter> parameters = new();
if (cmdletInfo.Parameters is null || cmdletInfo.Parameters.Count < 1)
{
return parameters;
}
foreach (KeyValuePair<string, ParameterMetadata> parameterMetadata in cmdletInfo.Parameters)
{
string parameterName = parameterMetadata.Key;
if (Constants.CommonParametersNames.Contains(parameterName))
{
continue;
}
var paramAttribInfo = GetParameterAtributeInfo(parameterMetadata.Value.Attributes);
string typeName = GetParameterTypeName(parameterMetadata.Value.ParameterType);
Parameter param = new(parameterMetadata.Value.Name, typeName);
param.DontShow = paramAttribInfo.DontShow;
param.SupportsWildcards = paramAttribInfo.Globbing;
param.HelpMessage = paramAttribInfo.HelpMessage ?? string.Empty;
foreach (KeyValuePair<string, ParameterSetMetadata> paramSet in parameterMetadata.Value.ParameterSets)
{
string parameterSetName = string.Compare(paramSet.Key, Constants.ParameterSetsAllName) == 0 ? Constants.ParameterSetsAll : paramSet.Key;
ParameterSetMetadata metadata = paramSet.Value;
var pSet = new Model.ParameterSet(parameterSetName);
pSet.Position = metadata.Position == int.MinValue ? Constants.NamedString : paramSet.Value.Position.ToString();
pSet.IsRequired = metadata.IsMandatory;
pSet.ValueFromPipeline = metadata.ValueFromPipeline;
pSet.ValueFromPipelineByPropertyName = metadata.ValueFromPipelineByPropertyName;
pSet.ValueFromRemainingArguments = metadata.ValueFromRemainingArguments;
param.ParameterSets.Add(pSet);
}
param.DefaultValue = GetParameterDefaultValueFromHelp(helpItem, param.Name);
param.Aliases = parameterMetadata.Value.Aliases.ToList();
string descriptionFromHelp = GetParameterDescriptionFromHelp(helpItem, param.Name) ?? param.HelpMessage ?? string.Empty;
param.Description = string.IsNullOrEmpty(descriptionFromHelp) ?
TransformUtils.GetParameterTemplateString(param.Name) :
descriptionFromHelp.Trim();
parameters.Add(param);
}
return parameters.OrderBy(param => param.Name);
}
protected static IEnumerable<Example> GetExamples(dynamic? helpItem, bool addDefaultString)
{
List<Example> examples = new();
if (addDefaultString)
{
Example exp = new(
Constants.Example1,
Constants.FillInExampleDescription
);
examples.Add(exp);
}
else
{
int exampleCounter = 1;
var examplesArray = helpItem?.examples?.example;
if (examplesArray is not null)
{
Collection<PSObject> examplesAsCollection = MakePSObjectEnumerable(examplesArray);
foreach (dynamic item in examplesAsCollection)
{
string title = item.title.ToString().Trim(' ', '-').Replace($"Example {exampleCounter}: ", string.Empty);
Example exp = new(
title,
GetExampleDetailFromItem(item)
);
examples.Add(exp);
exampleCounter++;
}
}
}
return examples;
}
/// <summary>
/// Retrieve the example string from an item.
/// This checks 3 different possible properties:
/// - code
/// - remarks
/// and constructs a string representing the example.
/// introduction is excluded (it seems to be just 'PS >')
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
static string GetExampleDetailFromItem(dynamic? item)
{
StringBuilder sb = Constants.StringBuilderPool.Get();
if (item?.code is not null)
{
sb.AppendLine(item.code.ToString().Trim());
}
if (item?.remarks is not null)
{
var description = GetStringFromDescriptionArray(item.remarks);
// If we found something in code, be sure to separate it with a newline.
if (sb.Length > 0)
{
sb.AppendLine();
}
sb.AppendLine(description);
}
try
{
return sb.ToString().Trim();
}
finally
{
Constants.StringBuilderPool.Return(sb);
}
}
protected static List<Links> GetRelatedLinks(dynamic? helpItem)
{
List<Links> links = new();
if (helpItem?.relatedLinks?.navigationLink is not null)
{
Collection<PSObject> navigationLinkCollection = MakePSObjectEnumerable(helpItem.relatedLinks.navigationLink);
foreach (dynamic navlink in navigationLinkCollection)
{
var uri = navlink?.uri is null ? string.Empty : navlink.uri.ToString();
var linkText = navlink?.linkText is null ? string.Empty : navlink.linkText.ToString();
links.Add(new Links(uri, linkText));
}
}
return links;
}
protected IEnumerable<SyntaxItem> GetSyntaxItem(CommandInfo? cmdletInfo, dynamic? helpItem)
{
List<SyntaxItem> syntaxItems = new();
if (cmdletInfo is null)
{
return syntaxItems;
}
foreach (CommandParameterSetInfo parameterSetInfo in cmdletInfo.ParameterSets)
{
SyntaxItem syn = new(cmdletInfo.Name, parameterSetInfo.Name, parameterSetInfo.IsDefault);
// Take the positional parameters first, and order them by position.
foreach (CommandParameterInfo paramInfo in parameterSetInfo.Parameters.Where(p => p.Position != int.MinValue).OrderBy(p => p.Position))
{
if (IsNotCommonParameter(paramInfo.Name)) {
syn.SyntaxParameters.Add(
new SyntaxParameter(
paramInfo.Name,
GetParameterTypeNameForSyntax(paramInfo.ParameterType, paramInfo.Attributes),
paramInfo.Position == int.MinValue ? "named" : paramInfo.Position.ToString(),
paramInfo.IsMandatory,
paramInfo.Position != int.MinValue,
string.Compare(paramInfo.ParameterType.Name, "SwitchParameter", true) == 0)
);
}
Parameter param = GetParameterInfo(cmdletInfo, helpItem, paramInfo);
syn.AddParameter(param);
}
// now take the named parameters.
foreach (CommandParameterInfo paramInfo in parameterSetInfo.Parameters.Where(p => p.Position == int.MinValue))
{
if (IsNotCommonParameter(paramInfo.Name)) {
var sParm = new SyntaxParameter(
paramInfo.Name,
GetParameterTypeNameForSyntax(paramInfo.ParameterType, paramInfo.Attributes),
paramInfo.Position == int.MinValue ? "named" : paramInfo.Position.ToString(),
paramInfo.IsMandatory,
paramInfo.Position != int.MinValue,
string.Compare(paramInfo.ParameterType.Name, "SwitchParameter", true) == 0);
syn.SyntaxParameters.Add(sParm);
}
Parameter param = GetParameterInfo(cmdletInfo, helpItem, paramInfo);
syn.AddParameter(param);
}
syntaxItems.Add(syn);
}
return syntaxItems;
}
private bool IsNotCommonParameter(string name)
{
return ! Constants.CommonParametersNames.Contains(name);
}
private string GetParameterTypeNameForSyntax(Type type, IEnumerable<Attribute> attributes)
{
string parameterTypeString;
PSTypeNameAttribute typeName;
if (attributes != null && (typeName = attributes.OfType<PSTypeNameAttribute>().FirstOrDefault()) != null)
{
// If we have a PSTypeName specified on the class, we assume it has a more useful type than the actual
// parameter type. This is a reasonable assumption, the parameter binder does honor this attribute.
//
// This typename might be long, e.g.:
// Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process
// System.Management.ManagementObject#root\cimv2\Win32_Process
// To shorten this, we will drop the namespaces, both on the .Net side and the CIM/WMI side:
// CimInstance#Win32_Process
// If our regex doesn't match, we'll just use the full name.
var match = Regex.Match(typeName.PSTypeName, "(.*\\.)?(?<NetTypeName>.*)#(.*[/\\\\])?(?<CimClassName>.*)");
if (match.Success)
{
parameterTypeString = match.Groups["NetTypeName"].Value + "#" + match.Groups["CimClassName"].Value;
}
else
{
parameterTypeString = typeName.PSTypeName;
// Drop the namespace from the typename, if any.
var lastDotIndex = parameterTypeString.LastIndexOf('.');
if (lastDotIndex != -1 && lastDotIndex + 1 < parameterTypeString.Length)
{
parameterTypeString = parameterTypeString.Substring(lastDotIndex + 1);
}
}
// If the type is really an array, but the typename didn't include [], then add it.
if (type.IsArray && !parameterTypeString.Contains("[]"))
{
var t = type;
while (t.IsArray)
{
parameterTypeString += "[]";
t = t.GetElementType();
}
}
}
else
{
Type parameterType = Nullable.GetUnderlyingType(type) ?? type;
// don't over abbreviate the type if it's a switch parameter, since we don't print it in the syntax.
if (parameterType == typeof(System.Management.Automation.SwitchParameter))
{
parameterTypeString = "SwitchParameter";
}
else
{
parameterTypeString = GetAbbreviatedType(parameterType);
}
}
return parameterTypeString;
}
/// <summary>
/// Build syntax parameter type or parameter type to string.
/// </summary>
/// <param name="sb">StringBuilder</param>
/// <param name="type">The type to be abbreviated</param>
/// <param name="abbreviate">
/// Try get abbreviated name.
/// e.g.) `System.Int32` -> `int`
/// </param>
/// <param name="dropNamespace">
/// Build type descriptor as no namespace.
/// </param>
/// <param name="fromNested">
/// Indicates that the <paramref name="type"/> is the type of the nesting source.
/// </param>
private static void BuildTypeString(StringBuilder sb, Type? type, bool abbreviate, bool dropNamespace, bool fromNested = false)
{
if (type is null)
{
return;
}
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
BuildTypeString(sb, type.GetGenericTypeDefinition(), abbreviate, dropNamespace);
var genericArgs = type.GetGenericArguments();
sb.Append('[');
for (var i = 0; i < genericArgs.Length; i++)
{
if (i > 0) sb.Append(',');
BuildTypeString(sb, genericArgs[i], abbreviate, dropNamespace);
}
sb.Append(']');
}
else if (type.IsArray)
{
BuildTypeString(sb, type.GetElementType(), abbreviate, dropNamespace);
sb.Append('[')
.Append(',', type.GetArrayRank() - 1)
.Append(']');
}
else
{
if (abbreviate && TransformUtils.TryGetTypeAbbreviation(type.FullName, out string abbreviatedName))
{
sb.Append(abbreviatedName);
return;
}
if (!dropNamespace && !string.IsNullOrEmpty(type.Namespace))
{
sb.Append(type.Namespace)
.Append('.');
}
// Indicates whether the "`n" sign at the end of a generic type name can be omitted
// e.g.) System.Collections.Generic.Dictionary`2[TKey, TValue]
// ^^ Can ommit
bool canOmmitGenericTailingSign = true;
if (type.IsNested)
{
var reflectedType = type.ReflectedType;
// `System.Collections.Generic.Dictionary`2+Enumerator[TKey,TValue]`
// ^^^^^^^^^^^^
BuildTypeString(sb, reflectedType, abbreviate, dropNamespace: true, fromNested: true);
sb.Append('+');
// Nested classe cannot omit the mark if the origin class is a generic type
// e.g.)
// Namespace.ClassA+Nested`1[T]
// ^^ Can ommit
// Namespace.ClassB`1+Nested`1[T1,T2]
// ^^ ^^ Cannot ommit
canOmmitGenericTailingSign = !(reflectedType?.IsGenericType ?? false);
}
if (!fromNested && canOmmitGenericTailingSign)
{
var backtickPosition = type.Name.LastIndexOf('`');
sb.Append(backtickPosition > 0 ? type.Name.Remove(backtickPosition) : type.Name);
}
else
{
sb.Append(type.Name);
}
}
}
private static string GetAbbreviatedType(Type type)
{
StringBuilder sb = Constants.StringBuilderPool.Get();
try
{
BuildTypeString(sb,
Nullable.GetUnderlyingType(type) ?? type,
abbreviate: true,
dropNamespace: true);
return sb.ToString();
}
finally
{
Constants.StringBuilderPool.Return(sb);
}
}
private string GetParameterTypeName(Type type)
{
StringBuilder sb = Constants.StringBuilderPool.Get();
try
{
BuildTypeString(sb,
Nullable.GetUnderlyingType(type) ?? type,
abbreviate: false,
dropNamespace: !Settings.UseFullTypeName);
return sb.ToString();
}
finally
{
Constants.StringBuilderPool.Return(sb);
}
}
protected Parameter GetParameterInfo(CommandInfo? cmdletInfo, dynamic? helpItem, CommandParameterInfo paramInfo)
{
var paramAttribInfo = GetParameterAtributeInfo(paramInfo.Attributes);
string typeName = GetParameterTypeName(paramInfo.ParameterType);
Parameter param = new(paramInfo.Name, typeName);
string descriptionFromHelp = GetParameterDescriptionFromHelp(helpItem, param.Name) ?? paramAttribInfo.HelpMessage ?? string.Empty;
param.Description = string.IsNullOrEmpty(descriptionFromHelp) ?
TransformUtils.GetParameterTemplateString(param.Name) :
descriptionFromHelp;
param.Aliases = paramInfo.Aliases.ToList();
param.ParameterSets.ForEach(x => x.IsRequired = paramInfo.IsMandatory);
string defaultValueFromHelp = GetParameterDefaultValueFromHelp(helpItem, param.Name);
param.DefaultValue = string.IsNullOrEmpty(defaultValueFromHelp) ?
Constants.NoneString :
defaultValueFromHelp;
return param;
}
internal class ParameterAttributeInfo
{
internal bool DontShow { get; set; }
internal bool PipelineInput { get; set; }
internal bool Required { get; set; }
internal bool Globbing { get; set; }
internal string Position { get; set; }
internal string? HelpMessage { get; set; }
public ParameterAttributeInfo(
bool dontShow,
bool pipelineInput,
bool required,
string position,
string? helpMessage,
bool globbing)
{
DontShow = dontShow;
PipelineInput = pipelineInput;
Required = required;
Position = position;
HelpMessage = helpMessage;
Globbing = globbing;
}
}
protected static ParameterAttributeInfo GetParameterAtributeInfo(IEnumerable<Attribute> attributes)
{
bool dontShow = false;
bool pipelineInput = false;
string position = Constants.NamedString;
bool required = false;
string? helpMessage = null;
bool globbing = false;
IList<string> acceptedValues;
foreach (var attrib in attributes)
{
switch (attrib)
{
case ParameterAttribute parameterAttribute:
dontShow = parameterAttribute.DontShow;
pipelineInput = parameterAttribute.ValueFromPipeline | parameterAttribute.ValueFromPipelineByPropertyName;
position = parameterAttribute.Position == int.MinValue ? Constants.NamedString : parameterAttribute.Position.ToString();
required = parameterAttribute.Mandatory;
helpMessage = parameterAttribute.HelpMessage;
break;
case SupportsWildcardsAttribute:
globbing = true;
break;
case ValidateSetAttribute validateSetAttribute:
acceptedValues = validateSetAttribute.ValidValues;
break;
}
}
return new ParameterAttributeInfo(dontShow, pipelineInput, required, position, helpMessage, globbing);
}
protected static IEnumerable<string> GetParameterSetsOfParameter(string parameterName, CommandInfo cmdletInfo)
{
if (cmdletInfo.Parameters.TryGetValue(parameterName, out ParameterMetadata? paramMetadata))
{
if (paramMetadata is not null)
{
return paramMetadata.ParameterSets.Keys;
}
else
{
return Constants.EmptyStringList;
}
}
return Constants.EmptyStringList;
}
protected static string? GetParameterDescriptionFromHelp(dynamic? helpItem, string parameterName)
{
if (helpItem?.parameters?.parameter == null)
{
return null;
}
Collection<PSObject>? parameterAsCollection = MakePSObjectEnumerable(helpItem.parameters.parameter);
foreach (dynamic parameter in parameterAsCollection)
{
if (string.Equals(parameter.name.ToString(), parameterName, StringComparison.OrdinalIgnoreCase))
{
var paramDescription = GetStringFromDescriptionArray(parameter.description);
return paramDescription == string.Empty ? null : paramDescription;
}
}
return null;
}
protected static string GetParameterDefaultValueFromHelp(dynamic? helpItem, string parameterName)
{
if (helpItem?.parameters?.parameter == null)
{
return string.Empty;
}
Collection<PSObject>? parameterAsCollection = MakePSObjectEnumerable(helpItem.parameters.parameter);
foreach (dynamic parameter in parameterAsCollection)
{
if (string.Equals(parameter.name.ToString(), parameterName, StringComparison.OrdinalIgnoreCase))
{
return parameter.defaultValue is null ? string.Empty : parameter.defaultValue.ToString();
}
}
return string.Empty;
}
protected static string? GetNotes(dynamic? helpItem, bool addDefaultString)
{
if (addDefaultString)
{
return Constants.FillInNotes;
}
else
{
return helpItem?.alertSet?.alert is not null ?
GetStringFromDescriptionArray(helpItem.alertSet.alert) :
string.Empty;
}
}
protected static string GetDescription(dynamic? helpItem, bool addDefaultStrings)
{
if (addDefaultStrings)
{
return Constants.FillInDescription;
}
else
{
if (helpItem is null)
{
throw new ArgumentNullException(nameof(helpItem));
}
return GetStringFromDescriptionArray(helpItem.description);
}
}
protected static string GetSynopsis(dynamic? helpItem, bool addDefaultStrings)
{
if (addDefaultStrings)
{
return Constants.FillInSynopsis;
}
else
{
return helpItem is not null ? helpItem.Synopsis.ToString() : throw new ArgumentNullException(nameof(helpItem));
}
}
protected List<InputOutput> GetInputOutputItemsFromHelp(dynamic typesInfo)
{
dynamic ioTypes = typesInfo;
List<InputOutput> itemList = new();
if (ioTypes is IEnumerable<PSObject>)
{
foreach (dynamic ioType in typesInfo)
{
string typeName = FixUpTypeName(ioType.type.name?.Split()?[0] ?? string.Empty);
if (! string.IsNullOrEmpty(typeName) && string.Compare(typeName, "None", true) != 0)
{
string description = GetStringFromDescriptionArray(ioType.description)?.Trim() ?? string.Empty;
itemList.Add(new InputOutput(typeName, string.IsNullOrEmpty(description) ? Constants.FillInDescription : description));
}
}
}
else if (ioTypes is PSObject)
{
if (ioTypes.type.name is string name)
{
name = name.Trim();
// Sometimes, help will return lines which have embedded newlines.
// these are really multiple entries, so split them here.
if (name.IndexOf("\n") == -1 && string.Compare(name, "None", true) != 0)
{
itemList.Add(new InputOutput(FixUpTypeName(name), Constants.FillInDescription));
}
else
{
foreach(var tName in name.Replace("\\r","").Split('\n'))
{
if (string.Compare(tName, "None", true) != 0)
{
itemList.Add(new InputOutput(FixUpTypeName(tName), Constants.FillInDescription));
}
}
}
}
else
{
string typeName = FixUpTypeName(ioTypes.type.name.ToString());
if (! string.IsNullOrEmpty(typeName) && string.Compare(typeName, "None", true) != 0)
{
string description = GetStringFromDescriptionArray(ioTypes.description).Trim();
itemList.Add(new InputOutput(typeName, string.IsNullOrEmpty(description) ? Constants.FillInDescription : description));
}
}
}
return itemList;
}
// We have to remove carriage returns that might be present from help
// We also will remove trailing [] because we should generally return singletons
private string FixUpTypeName(string typename)
{
// If the type is a generic type, we need to remove the backtick and the number.
string fixedString = typename.Replace("System.Nullable`1[[", string.Empty).Trim();
int commaIndex = fixedString.IndexOf(',');
if (commaIndex >= 0)
{
fixedString = fixedString.Substring(0, commaIndex).Trim();
}
if (fixedString.EndsWith("[]"))
{
fixedString = fixedString.Remove(fixedString.Length - 2);
}
return fixedString;
}
protected static string GetStringFromDescriptionArray(dynamic? description)
{
if (description == null)
{
return string.Empty;
}
if (description is string)
{
return description;
}
if (description is not IEnumerable && description is PSObject)
{
return description.ToString();
}
StringBuilder sb = Constants.StringBuilderPool.Get();
try
{
foreach (dynamic line in description)
{
if (line is not char)
{
string text = line.text.ToString();
// Add semantic line break.
sb.AppendLine(text.Replace(". ", $".{Environment.NewLine}"));
}
}
return sb.ToString();
}
finally
{
Constants.StringBuilderPool.Return(sb);
}
}
private static Collection<PSObject> MakePSObjectEnumerable(dynamic psObject)
{
Collection<PSObject> forceEnumerable = new();
if (psObject is PSObject)
{
forceEnumerable = new Collection<PSObject>
{
psObject
};
}
else if (psObject is PSObject[])
{
forceEnumerable = new Collection<PSObject>();
foreach (var item in psObject)
{
forceEnumerable.Add(item);
}
}
else if (psObject is Collection<PSObject>)
{
return psObject;
}
else if (psObject is object[])
{
forceEnumerable = new Collection<PSObject>();
foreach (var item in psObject)
{
forceEnumerable.Add(new PSObject(item));
}
}
return forceEnumerable;
}
}
}