-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathPSResourceInfo.cs
More file actions
1974 lines (1699 loc) · 86.4 KB
/
PSResourceInfo.cs
File metadata and controls
1974 lines (1699 loc) · 86.4 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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using NuGet.Versioning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Text.Json;
using System.Xml;
using Microsoft.PowerShell.Commands;
using Dbg = System.Diagnostics.Debug;
namespace Microsoft.PowerShell.PSResourceGet.UtilClasses
{
#region Enums
public enum ResourceType
{
None,
Module,
Script,
Nupkg
}
public enum VersionType
{
NoVersion,
SpecificVersion,
VersionRange
}
public enum ScopeType
{
CurrentUser,
AllUsers
}
#endregion
#region ResourceIncludes
public sealed class ResourceIncludes
{
#region Properties
public string[] Cmdlet { get; }
public string[] Command { get; }
public string[] DscResource { get; }
public string[] Function { get; }
public string[] RoleCapability { get; }
public string[] Workflow { get; }
#endregion
#region Constructor
/// <summary>
/// Constructor
///
/// Provided hashtable has form:
/// Key: Cmdlet
/// Value: ArrayList of Cmdlet name strings
/// Key: Command
/// Value: ArrayList of Command name strings
/// Key: DscResource
/// Value: ArrayList of DscResource name strings
/// Key: Function
/// Value: ArrayList of Function name strings
/// Key: RoleCapability (deprecated for PSGetV3)
/// Value: ArrayList of RoleCapability name strings
/// Key: Workflow (deprecated for PSGetV3)
/// Value: ArrayList of Workflow name strings
/// </summary>
/// <param name="includes">Hashtable of PSGet includes</param>
internal ResourceIncludes(Hashtable includes)
{
if (includes == null) { return; }
Cmdlet = GetHashTableItem(includes, nameof(Cmdlet));
Command = GetHashTableItem(includes, nameof(Command));
DscResource = GetHashTableItem(includes, nameof(DscResource));
Function = GetHashTableItem(includes, nameof(Function));
RoleCapability = GetHashTableItem(includes, nameof(RoleCapability));
Workflow = GetHashTableItem(includes, nameof(Workflow));
}
internal ResourceIncludes()
{
Cmdlet = Utils.EmptyStrArray;
Command = Utils.EmptyStrArray;
DscResource = Utils.EmptyStrArray;
Function = Utils.EmptyStrArray;
RoleCapability = Utils.EmptyStrArray;
Workflow = Utils.EmptyStrArray;
}
#endregion
#region Public methods
public Hashtable ConvertToHashtable()
{
var hashtable = new Hashtable
{
{ nameof(Cmdlet), Cmdlet },
{ nameof(Command), Command },
{ nameof(DscResource), DscResource },
{ nameof(Function), Function },
{ nameof(RoleCapability), RoleCapability },
{ nameof(Workflow), Workflow }
};
return hashtable;
}
#endregion
#region Private methods
private string[] GetHashTableItem(
Hashtable table,
string name)
{
if (table.ContainsKey(name) &&
table[name] is PSObject psObjectItem)
{
return Utils.GetStringArray(psObjectItem.BaseObject as ArrayList);
}
return null;
}
#endregion
}
#endregion
#region Dependency
public sealed class Dependency
{
#region Properties
public string Name { get; }
public VersionRange VersionRange { get; }
#endregion
#region Constructor
/// <summary>
/// Constructor
/// An object describes a package dependency
/// </summary>
public Dependency(string dependencyName, VersionRange dependencyVersionRange)
{
Name = dependencyName;
VersionRange = dependencyVersionRange;
}
#endregion
}
#endregion
#region PSCommandResourceInfo
public sealed class PSCommandResourceInfo
{
// this object will represent a Command or DSCResource
// included by the PSResourceInfo property
#region Properties
public string[] Names { get; }
public PSResourceInfo ParentResource { get; }
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="names">Name of the command or DSC resource</param>
/// <param name="parentResource">the parent module resource the command or dsc resource belongs to</param>
public PSCommandResourceInfo(string[] names, PSResourceInfo parentResource)
{
Names = names;
ParentResource = parentResource;
}
#endregion
}
#endregion
#region PSResourceInfo
public sealed class PSResourceInfo
{
#region Properties
public Dictionary<string, string> AdditionalMetadata { get; }
public string Author { get; set; }
public string CompanyName { get; set; }
public string Copyright { get; set; }
public Dependency[] Dependencies { get; set; }
public string Description { get; set; }
public Uri IconUri { get; set; }
public ResourceIncludes Includes { get; }
public DateTime? InstalledDate { get; set; }
public string InstalledLocation { get; set; }
public bool IsPrerelease { get; set; }
public Uri LicenseUri { get; set; }
public string Name { get; set; }
private string PowerShellGetFormatVersion { get; }
public string Prerelease { get; }
public Uri ProjectUri { get; set; }
public DateTime? PublishedDate { get; set; }
public string ReleaseNotes { get; set; }
public string Repository { get; set; }
public string RepositorySourceLocation { get; set; }
public string[] Tags { get; set; }
public ResourceType Type { get; }
public DateTime? UpdatedDate { get; }
public Version Version { get; }
#endregion
#region Constructors
private PSResourceInfo() { }
private PSResourceInfo(
Dictionary<string, string> additionalMetadata,
string author,
string companyName,
string copyright,
Dependency[] dependencies,
string description,
Uri iconUri,
ResourceIncludes includes,
DateTime? installedDate,
string installedLocation,
bool isPrerelease,
Uri licenseUri,
string name,
string powershellGetFormatVersion,
string prerelease,
Uri projectUri,
DateTime? publishedDate,
string releaseNotes,
string repository,
string repositorySourceLocation,
string[] tags,
ResourceType type,
DateTime? updatedDate,
Version version)
{
AdditionalMetadata = additionalMetadata ?? new Dictionary<string, string>();
Author = author ?? string.Empty;
CompanyName = companyName ?? string.Empty;
Copyright = copyright ?? string.Empty;
Dependencies = dependencies ?? new Dependency[0];
Description = description ?? string.Empty;
IconUri = iconUri;
Includes = includes ?? new ResourceIncludes();
InstalledDate = installedDate;
InstalledLocation = installedLocation ?? string.Empty;
IsPrerelease = isPrerelease;
LicenseUri = licenseUri;
Name = name ?? string.Empty;
PowerShellGetFormatVersion = powershellGetFormatVersion ?? string.Empty;
Prerelease = prerelease ?? string.Empty;
ProjectUri = projectUri;
PublishedDate = publishedDate;
ReleaseNotes = releaseNotes ?? string.Empty;
Repository = repository ?? string.Empty;
RepositorySourceLocation = repositorySourceLocation ?? string.Empty;
Tags = tags ?? Utils.EmptyStrArray;
Type = type;
UpdatedDate = updatedDate;
Version = version ?? new Version();
}
#endregion
#region Private fields
private static readonly char[] Delimeter = {' ', ','};
#endregion
#region Public static methods
/// <summary>
/// Writes the PSGetResourceInfo properties to the specified file path as a
/// PowerShell serialized xml file, maintaining compatibility with
/// PSResourceGet file format.
/// </summary>
public bool TryWrite(
string filePath,
out string errorMsg)
{
errorMsg = string.Empty;
if (string.IsNullOrWhiteSpace(filePath))
{
errorMsg = "TryWritePSGetInfo: Invalid file path. Filepath cannot be empty or whitespace.";
return false;
}
try
{
var infoXml = PSSerializer.Serialize(
source: ConvertToCustomObject(),
depth: 5);
System.IO.File.WriteAllText(
path: filePath,
contents: infoXml);
return true;
}
catch(Exception ex)
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryWritePSGetInfo: Cannot convert and write the PSResourceGet information to file, with error: {0}",
ex.Message);
return false;
}
}
/// <summary>
/// Reads a PSGet resource xml (PowerShell serialized) file and returns
/// a PSResourceInfo object containing the file contents.
/// </summary>
public static bool TryRead(
string filePath,
out PSResourceInfo psGetInfo,
out string errorMsg)
{
psGetInfo = null;
errorMsg = string.Empty;
if (string.IsNullOrWhiteSpace(filePath))
{
errorMsg = "TryReadPSGetInfo: Invalid file path. Filepath cannot be empty or whitespace.";
return false;
}
try
{
// Read and deserialize information xml file.
var psObjectInfo = (PSObject) PSSerializer.Deserialize(
System.IO.File.ReadAllText(
filePath));
var additionalMetadata = GetProperty<Dictionary<string,string>>(nameof(PSResourceInfo.AdditionalMetadata), psObjectInfo);
Version version = GetVersionInfo(psObjectInfo, additionalMetadata, out string prerelease);
psGetInfo = new PSResourceInfo(
additionalMetadata: additionalMetadata,
author: GetStringProperty(nameof(PSResourceInfo.Author), psObjectInfo),
companyName: GetStringProperty(nameof(PSResourceInfo.CompanyName), psObjectInfo),
copyright: GetStringProperty(nameof(PSResourceInfo.Copyright), psObjectInfo),
dependencies: GetDependencies(GetProperty<ArrayList>(nameof(PSResourceInfo.Dependencies), psObjectInfo)),
description: GetStringProperty(nameof(PSResourceInfo.Description), psObjectInfo),
iconUri: GetProperty<Uri>(nameof(PSResourceInfo.IconUri), psObjectInfo),
includes: new ResourceIncludes(GetProperty<Hashtable>(nameof(PSResourceInfo.Includes), psObjectInfo)),
installedDate: GetProperty<DateTime>(nameof(PSResourceInfo.InstalledDate), psObjectInfo),
installedLocation: GetStringProperty(nameof(PSResourceInfo.InstalledLocation), psObjectInfo),
isPrerelease: GetProperty<bool>(nameof(PSResourceInfo.IsPrerelease), psObjectInfo),
licenseUri: GetProperty<Uri>(nameof(PSResourceInfo.LicenseUri), psObjectInfo),
name: GetStringProperty(nameof(PSResourceInfo.Name), psObjectInfo),
powershellGetFormatVersion: GetStringProperty(nameof(PSResourceInfo.PowerShellGetFormatVersion), psObjectInfo),
prerelease: prerelease,
projectUri: GetProperty<Uri>(nameof(PSResourceInfo.ProjectUri), psObjectInfo),
publishedDate: GetProperty<DateTime>(nameof(PSResourceInfo.PublishedDate), psObjectInfo),
releaseNotes: GetStringProperty(nameof(PSResourceInfo.ReleaseNotes), psObjectInfo),
repository: GetStringProperty(nameof(PSResourceInfo.Repository), psObjectInfo),
repositorySourceLocation: GetStringProperty(nameof(PSResourceInfo.RepositorySourceLocation), psObjectInfo),
tags: Utils.GetStringArray(GetProperty<ArrayList>(nameof(PSResourceInfo.Tags), psObjectInfo)),
type: Enum.TryParse(
GetProperty<object>(nameof(PSResourceInfo.Type), psObjectInfo).ToString() ?? nameof(ResourceType.Module),
out ResourceType currentReadType)
? currentReadType : ResourceType.Module,
updatedDate: GetProperty<DateTime>(nameof(PSResourceInfo.UpdatedDate), psObjectInfo),
version: version);
return true;
}
catch(Exception ex)
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryReadPSGetInfo: Cannot read the PSResourceGet information file with error: {0}",
ex.Message);
return false;
}
}
private static string GetStringProperty(
string name,
PSObject psObjectInfo)
{
return GetProperty<string>(name, psObjectInfo) ?? string.Empty;
}
private static Version GetVersionInfo(
PSObject psObjectInfo,
Dictionary<string, string> additionalMetadata,
out string prerelease)
{
string versionString = GetProperty<string>(nameof(PSResourceInfo.Version), psObjectInfo);
prerelease = String.Empty;
if (!String.IsNullOrEmpty(versionString) ||
additionalMetadata.TryGetValue("NormalizedVersion", out versionString))
{
string pkgVersion = versionString;
if (versionString.Contains("-"))
{
// versionString: "1.2.0-alpha1"
string[] versionStringParsed = versionString.Split('-');
if (versionStringParsed.Length == 1)
{
// versionString: "1.2.0-" (unlikely, at least should not be from our PSResourceInfo.TryWrite())
pkgVersion = versionStringParsed[0];
}
else
{
// versionStringParsed.Length > 1 (because string contained '-' so couldn't be 0)
// versionString: "1.2.0-alpha1"
pkgVersion = versionStringParsed[0];
prerelease = versionStringParsed[1];
}
}
// at this point, version is normalized (i.e either "1.2.0" (if part of prerelease) or "1.2.0.0" otherwise)
// parse the pkgVersion parsed out above into a System.Version object
if (!Version.TryParse(pkgVersion, out Version parsedVersion))
{
prerelease = String.Empty;
return null;
}
else
{
return parsedVersion;
}
}
// version could not be parsed as string, it was written to XML file as a System.Version object
// V3 code briefly did so, I believe so we provide support for it
prerelease = String.Empty;
return GetProperty<Version>(nameof(PSResourceInfo.Version), psObjectInfo);
}
/// <summary>
/// Converts XML entry to PSResourceInfo instance
/// used for V2 Server API call find response conversion to PSResourceInfo object
/// </summary>
public static bool TryConvertFromXml(
XmlNode entry,
out PSResourceInfo psGetInfo,
PSRepositoryInfo repository,
out string errorMsg)
{
psGetInfo = null;
errorMsg = String.Empty;
if (entry == null)
{
errorMsg = "TryConvertXmlToPSResourceInfo: Invalid XmlNodeList object. Object cannot be null.";
return false;
}
try
{
Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
var entryChildNodes = entry.ChildNodes;
foreach (XmlElement entryChild in entryChildNodes)
{
var entryKey = entryChild.LocalName;
// For repositories such as JFrog's Artifactory, there is no 'Id' property, just 'title' (which contains the name of the pkg).
// However, other repos, like PSGallery include the name of the pkg in the 'Id' property and leave 'title' empty.
// In JFrog's Artifactory, 'title' exists both as a child of the 'entry' node and as a child of the 'properties' node,
// though sometimes 'title' under the 'properties' node can be empty (so default to using the former).
if (entryKey.Equals("title"))
{
metadata["Id"] = entryChild.InnerText;
}
else if (entryKey.Equals("properties"))
{
var propertyChildNodes = entryChild.ChildNodes;
foreach (XmlElement propertyChild in propertyChildNodes)
{
var propertyKey = propertyChild.LocalName;
var propertyValue = propertyChild.InnerText;
if (propertyKey.Equals("Title"))
{
if (!metadata.ContainsKey("Id"))
{
metadata["Id"] = propertyValue;
}
}
if (propertyKey.Equals("Version"))
{
metadata[propertyKey] = ParseHttpVersion(propertyValue, out string prereleaseLabel);
metadata["Prerelease"] = prereleaseLabel;
}
else if (propertyKey.EndsWith("Url"))
{
metadata[propertyKey] = ParseHttpUrl(propertyValue) as Uri;
}
else if (propertyKey.Equals("Tags"))
{
metadata[propertyKey] = propertyValue.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
else if (propertyKey.Equals("Published"))
{
metadata[propertyKey] = ParseHttpDateTime(propertyValue);
}
else if (propertyKey.Equals("Dependencies"))
{
metadata[propertyKey] = ParseHttpDependencies(propertyValue);
}
else if (propertyKey.Equals("IsPrerelease"))
{
bool.TryParse(propertyValue, out bool isPrerelease);
metadata[propertyKey] = isPrerelease;
}
else if (propertyKey.Equals("NormalizedVersion"))
{
if (!NuGetVersion.TryParse(propertyValue, out NuGetVersion parsedNormalizedVersion))
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryReadPSGetInfo: Cannot parse NormalizedVersion");
parsedNormalizedVersion = new NuGetVersion("1.0.0.0");
}
metadata[propertyKey] = parsedNormalizedVersion;
}
else
{
metadata[propertyKey] = propertyValue;
}
}
}
}
var typeInfo = ParseHttpMetadataType(metadata["Tags"] as string[], out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames);
var resourceHashtable = new Hashtable {
{ nameof(PSResourceInfo.Includes.Command), new PSObject(commandNames) },
{ nameof(PSResourceInfo.Includes.Cmdlet), new PSObject(cmdletNames) },
{ nameof(PSResourceInfo.Includes.DscResource), new PSObject(dscResourceNames) }
};
var additionalMetadataHashtable = new Dictionary<string, string>();
// Only add NormalizedVersion to additionalMetadata if server response included it
if (metadata.ContainsKey("NormalizedVersion")) {
additionalMetadataHashtable.Add("NormalizedVersion", metadata["NormalizedVersion"].ToString());
}
var includes = new ResourceIncludes(resourceHashtable);
psGetInfo = new PSResourceInfo(
additionalMetadata: additionalMetadataHashtable,
author: metadata["Authors"] as String,
companyName: metadata["CompanyName"] as String,
copyright: metadata["Copyright"] as String,
dependencies: metadata["Dependencies"] as Dependency[],
description: metadata["Description"] as String,
iconUri: metadata["IconUrl"] as Uri,
includes: includes,
installedDate: null,
installedLocation: null,
isPrerelease: (bool) metadata["IsPrerelease"],
licenseUri: metadata["LicenseUrl"] as Uri,
name: metadata["Id"] as String,
powershellGetFormatVersion: null,
prerelease: metadata["Prerelease"] as String,
projectUri: metadata["ProjectUrl"] as Uri,
publishedDate: metadata["Published"] as DateTime?,
releaseNotes: metadata["ReleaseNotes"] as String,
repository: repository.Name,
repositorySourceLocation: repository.Uri.ToString(),
tags: metadata["Tags"] as string[],
type: typeInfo,
updatedDate: null,
version: metadata["Version"] as Version);
return true;
}
catch (Exception ex)
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryConvertFromXml: Cannot parse PSResourceInfo from XmlNode with error: {0}",
ex.Message);
return false;
}
}
/// <summary>
/// Converts JsonDocument entry to PSResourceInfo instance
/// used for V3 Server API call find response conversion to PSResourceInfo object
/// </summary>
public static bool TryConvertFromJson(
JsonDocument pkgJson,
out PSResourceInfo psGetInfo,
PSRepositoryInfo repository,
out string errorMsg)
{
psGetInfo = null;
errorMsg = String.Empty;
if (pkgJson == null)
{
errorMsg = "TryConvertJsonToPSResourceInfo: Invalid json object. Object cannot be null.";
return false;
}
try
{
Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
JsonElement rootDom = pkgJson.RootElement;
// Version
if (rootDom.TryGetProperty("version", out JsonElement versionElement))
{
string versionValue = versionElement.ToString();
metadata["Version"] = ParseHttpVersion(versionValue, out string prereleaseLabel);
metadata["Prerelease"] = prereleaseLabel;
// ADO server response does not contain "isPrerelease" element, so we set it here.
metadata["IsPrerelease"] = !String.IsNullOrEmpty(prereleaseLabel);
if (!NuGetVersion.TryParse(versionValue, out NuGetVersion parsedNormalizedVersion))
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryReadPSGetInfo: Cannot parse NormalizedVersion");
parsedNormalizedVersion = new NuGetVersion("1.0.0.0");
}
metadata["NormalizedVersion"] = parsedNormalizedVersion;
}
// License Url
if (rootDom.TryGetProperty("licenseUrl", out JsonElement licenseUrlElement))
{
metadata["LicenseUrl"] = ParseHttpUrl(licenseUrlElement.ToString()) as Uri;
}
// Project Url
if (rootDom.TryGetProperty("projectUrl", out JsonElement projectUrlElement))
{
metadata["ProjectUrl"] = ParseHttpUrl(projectUrlElement.ToString()) as Uri;
}
// Icon Url
if (rootDom.TryGetProperty("iconUrl", out JsonElement iconUrlElement))
{
metadata["IconUrl"] = ParseHttpUrl(iconUrlElement.ToString()) as Uri;
}
// Tags
if (rootDom.TryGetProperty("tags", out JsonElement tagsElement))
{
string[] pkgTags = Utils.EmptyStrArray;
if (tagsElement.ValueKind == JsonValueKind.Array)
{
var arrayLength = tagsElement.GetArrayLength();
List<string> tags = new List<string>(arrayLength);
foreach (var tag in tagsElement.EnumerateArray())
{
tags.Add(tag.ToString());
}
pkgTags = tags.ToArray();
}
else if (tagsElement.ValueKind == JsonValueKind.String)
{
string tagStr = tagsElement.ToString();
pkgTags = tagStr.Split(Utils.WhitespaceSeparator, StringSplitOptions.RemoveEmptyEntries);
}
metadata["Tags"] = pkgTags;
}
// PublishedDate
if (rootDom.TryGetProperty("published", out JsonElement publishedElement))
{
metadata["PublishedDate"] = ParseHttpDateTime(publishedElement.ToString());
}
// Dependencies
// TODO, tracked via: https://github.com/PowerShell/PSResourceGet/issues/1169
// IsPrerelease
// NuGet.org repository's response does contain 'isPrerelease' element so it can be accquired and set here.
if (rootDom.TryGetProperty("isPrerelease", out JsonElement isPrereleaseElement))
{
metadata["IsPrerelease"] = isPrereleaseElement.GetBoolean();
}
// Author
if (rootDom.TryGetProperty("authors", out JsonElement authorsElement))
{
metadata["Authors"] = authorsElement.ToString();
// CompanyName
// CompanyName is not provided in v3 pkg metadata response, so we've just set it to the author,
// which is often the company
metadata["CompanyName"] = authorsElement.ToString();
}
// Copyright
if (rootDom.TryGetProperty("copyright", out JsonElement copyrightElement))
{
metadata["Copyright"] = copyrightElement.ToString();
}
// Description
if (rootDom.TryGetProperty("description", out JsonElement descriptiontElement))
{
metadata["Description"] = descriptiontElement.ToString();
}
// Id
if (rootDom.TryGetProperty("id", out JsonElement idElement))
{
metadata["Id"] = idElement.ToString();
}
// ReleaseNotes
if (rootDom.TryGetProperty("releaseNotes", out JsonElement releaseNotesElement)) {
metadata["ReleaseNotes"] = releaseNotesElement.ToString();
}
var additionalMetadataHashtable = new Dictionary<string, string>
{
{ "NormalizedVersion", metadata["NormalizedVersion"].ToString() }
};
psGetInfo = new PSResourceInfo(
additionalMetadata: additionalMetadataHashtable,
author: metadata["Authors"] as String,
companyName: metadata["CompanyName"] as String,
copyright: metadata["Copyright"] as String,
dependencies: metadata["Dependencies"] as Dependency[],
description: metadata["Description"] as String,
iconUri: null,
includes: null,
installedDate: null,
installedLocation: null,
isPrerelease: (bool)metadata["IsPrerelease"],
licenseUri: metadata["LicenseUrl"] as Uri,
name: metadata["Id"] as String,
powershellGetFormatVersion: null,
prerelease: metadata["Prerelease"] as String,
projectUri: metadata["ProjectUrl"] as Uri,
publishedDate: metadata["PublishedDate"] as DateTime?,
releaseNotes: metadata["ReleaseNotes"] as String,
repository: repository.Name,
repositorySourceLocation: repository.Uri.ToString(),
tags: metadata["Tags"] as string[],
type: ResourceType.None,
updatedDate: null,
version: metadata["Version"] as Version);
return true;
}
catch (Exception ex)
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryConvertFromJson: Cannot parse PSResourceInfo from json object with error: {0}",
ex.Message);
return false;
}
}
/// <summary>
/// Converts ContainerRegistry JsonDocument entry to PSResourceInfo instance
/// used for ContainerRegistry Server API call find response conversion to PSResourceInfo object
/// </summary>
public static bool TryConvertFromContainerRegistryJson(
string packageName,
JsonDocument packageMetadata,
ResourceType? resourceType,
out PSResourceInfo psGetInfo,
PSRepositoryInfo repository,
out string errorMsg)
{
psGetInfo = null;
errorMsg = String.Empty;
if (packageMetadata == null)
{
errorMsg = "TryConvertFromContainerRegistryJson: Invalid json object. Object cannot be null.";
return false;
}
try
{
Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
JsonElement rootDom = packageMetadata.RootElement;
metadata["IsPrerelease"] = false;
metadata["Prerelease"] = String.Empty;
string versionValue = String.Empty;
Version pkgVersion = null;
// Version
// For scripts (i.e with "Version" property) the version can contain prerelease label
// For nupkg only based packages the .nuspec's metadata attributes will be lowercase
if (rootDom.TryGetProperty("Version", out JsonElement scriptVersionElement) || rootDom.TryGetProperty("version", out scriptVersionElement))
{
versionValue = scriptVersionElement.ToString();
pkgVersion = ParseHttpVersion(versionValue, out string prereleaseLabel);
metadata["Version"] = pkgVersion;
metadata["Prerelease"] = prereleaseLabel;
metadata["IsPrerelease"] = !String.IsNullOrEmpty(prereleaseLabel);
}
else if(rootDom.TryGetProperty("ModuleVersion", out JsonElement moduleVersionElement))
{
// For modules (i.e with "ModuleVersion" property) it will just contain the numerical part not prerelease label, so we must find that from PrivateData.PSData.Prerelease entry
versionValue = moduleVersionElement.ToString();
pkgVersion = ParseHttpVersion(versionValue, out string prereleaseLabel);
metadata["Version"] = pkgVersion;
if (rootDom.TryGetProperty("PrivateData", out JsonElement versionPrivateDataElement) && versionPrivateDataElement.TryGetProperty("PSData", out JsonElement versionPSDataElement))
{
if (versionPSDataElement.TryGetProperty("Prerelease", out JsonElement pkgPrereleaseLabelElement) && !String.IsNullOrEmpty(pkgPrereleaseLabelElement.ToString().Trim()))
{
prereleaseLabel = pkgPrereleaseLabelElement.ToString().Trim();
versionValue += $"-{prereleaseLabel}";
metadata["Prerelease"] = prereleaseLabel;
metadata["IsPrerelease"] = true;
}
}
}
else
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryConvertFromContainerRegistryJson: Neither 'ModuleVersion' nor 'Version' could be found in package metadata");
return false;
}
if (!NuGetVersion.TryParse(versionValue, out NuGetVersion parsedNormalizedVersion) && pkgVersion == null)
{
errorMsg = string.Format(
CultureInfo.InvariantCulture,
@"TryConvertFromContainerRegistryJson: Cannot parse NormalizedVersion or System.Version from version in metadata.");
return false;
}
metadata["NormalizedVersion"] = parsedNormalizedVersion.ToNormalizedString();
// License Url
if (rootDom.TryGetProperty("LicenseUrl", out JsonElement licenseUrlElement) || rootDom.TryGetProperty("licenseUrl", out licenseUrlElement))
{
metadata["LicenseUrl"] = ParseHttpUrl(licenseUrlElement.ToString()) as Uri;
}
// Project Url
if (rootDom.TryGetProperty("ProjectUrl", out JsonElement projectUrlElement) || rootDom.TryGetProperty("projectUrl", out projectUrlElement))
{
metadata["ProjectUrl"] = ParseHttpUrl(projectUrlElement.ToString()) as Uri;
}
// Icon Url
if (rootDom.TryGetProperty("IconUrl", out JsonElement iconUrlElement) || rootDom.TryGetProperty("iconUrl", out iconUrlElement))
{
metadata["IconUrl"] = ParseHttpUrl(iconUrlElement.ToString()) as Uri;
}
// Tags
if (rootDom.TryGetProperty("Tags", out JsonElement tagsElement) || rootDom.TryGetProperty("tags", out tagsElement))
{
string[] pkgTags = Utils.EmptyStrArray;
if (tagsElement.ValueKind == JsonValueKind.Array)
{
var arrayLength = tagsElement.GetArrayLength();
List<string> tags = new List<string>(arrayLength);
foreach (var tag in tagsElement.EnumerateArray())
{
tags.Add(tag.ToString());
}
pkgTags = tags.ToArray();
}
else if (tagsElement.ValueKind == JsonValueKind.String)
{
string tagStr = tagsElement.ToString();
pkgTags = tagStr.Split(Utils.WhitespaceSeparator, StringSplitOptions.RemoveEmptyEntries);
}
metadata["Tags"] = pkgTags;
}
// PublishedDate
if (rootDom.TryGetProperty("Published", out JsonElement publishedElement))
{
metadata["PublishedDate"] = ParseHttpDateTime(publishedElement.ToString());
}
// IsPrerelease
if (rootDom.TryGetProperty("IsPrerelease", out JsonElement isPrereleaseElement))
{
metadata["IsPrerelease"] = isPrereleaseElement.GetBoolean();
}
// Author
if (rootDom.TryGetProperty("Authors", out JsonElement authorsElement) || rootDom.TryGetProperty("authors", out authorsElement) || rootDom.TryGetProperty("Author", out authorsElement))
{
metadata["Authors"] = authorsElement.ToString();
}
if (rootDom.TryGetProperty("CompanyName", out JsonElement companyNameElement))
{
metadata["CompanyName"] = companyNameElement.ToString();
}
else
{
// if CompanyName property is not provided set it to the Author value which is often the same.
metadata["CompanyName"] = metadata["Authors"];
}
// Copyright
if (rootDom.TryGetProperty("Copyright", out JsonElement copyrightElement) || rootDom.TryGetProperty("copyright", out copyrightElement))
{
metadata["Copyright"] = copyrightElement.ToString();
}
// Description
if (rootDom.TryGetProperty("Description", out JsonElement descriptiontElement) || rootDom.TryGetProperty("description", out descriptiontElement))
{
metadata["Description"] = descriptiontElement.ToString();
}
// ReleaseNotes
if (rootDom.TryGetProperty("ReleaseNotes", out JsonElement releaseNotesElement) || rootDom.TryGetProperty("releaseNotes", out releaseNotesElement))
{
metadata["ReleaseNotes"] = releaseNotesElement.ToString();
}
// Dependencies
if (rootDom.TryGetProperty("RequiredModules", out JsonElement requiredModulesElement))
{
metadata["Dependencies"] = ParseContainerRegistryDependencies(requiredModulesElement, out errorMsg).ToArray();
}
if (string.Equals(packageName, "Az", StringComparison.OrdinalIgnoreCase) || string.Equals(packageName, "Azpreview", StringComparison.OrdinalIgnoreCase) || packageName.StartsWith("Az.", StringComparison.OrdinalIgnoreCase))
{
if (rootDom.TryGetProperty("ModuleList", out JsonElement moduleListDepsElement))
{
metadata["Dependencies"] = ParseContainerRegistryDependencies(moduleListDepsElement, out errorMsg).ToArray();
}
else if (rootDom.TryGetProperty("PrivateData", out JsonElement depsPrivateDataElement) && depsPrivateDataElement.TryGetProperty("PSData", out JsonElement depsPSDataElement))
{
if (depsPSDataElement.TryGetProperty("ModuleList", out JsonElement privateDataModuleListDepsElement))
{
metadata["Dependencies"] = ParseContainerRegistryDependencies(privateDataModuleListDepsElement, out errorMsg).ToArray();
}
}
}
if (rootDom.TryGetProperty("PrivateData", out JsonElement privateDataElement) && privateDataElement.ValueKind == JsonValueKind.Object && privateDataElement.TryGetProperty("PSData", out JsonElement psDataElement))
{
// some properties that may be in PrivateData.PSData: LicenseUri, ProjectUri, IconUri, ReleaseNotes
if (!metadata.ContainsKey("LicenseUrl") && psDataElement.TryGetProperty("LicenseUri", out JsonElement psDataLicenseUriElement))
{
metadata["LicenseUrl"] = ParseHttpUrl(psDataLicenseUriElement.ToString()) as Uri;