-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathNuGetServerAPICalls.cs
More file actions
1033 lines (878 loc) · 45.9 KB
/
NuGetServerAPICalls.cs
File metadata and controls
1033 lines (878 loc) · 45.9 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 Microsoft.PowerShell.PSResourceGet.UtilClasses;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using NuGet.Versioning;
using System.Threading.Tasks;
using System.Xml;
using System.Net;
using System.Runtime.ExceptionServices;
using System.Management.Automation;
using System.Collections.Concurrent;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
internal class NuGetServerAPICalls : ServerApiCall
{
#region Members
public override PSRepositoryInfo Repository { get; set; }
private readonly PSCmdlet _cmdletPassedIn;
private HttpClient _sessionClient { get; set; }
private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{};
public FindResponseType FindResponseType = FindResponseType.ResponseString;
#endregion
#region Constructor
public NuGetServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base (repository, networkCredential)
{
this.Repository = repository;
_cmdletPassedIn = cmdletPassedIn;
HttpClientHandler handler = new HttpClientHandler()
{
Credentials = networkCredential
};
_sessionClient = new HttpClient(handler);
_sessionClient.Timeout = TimeSpan.FromMinutes(10);
_sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString);
}
#endregion
#region Overridden Methods
public override Task<FindResults> FindVersionAsync(string packageName, string version, ResourceType type, ConcurrentQueue<ErrorRecord> errorMsgs, ConcurrentQueue<string> warningMsgs, ConcurrentQueue<string> debugMsgs, ConcurrentQueue<string> verboseMsgs)
{
throw new NotImplementedException("FindVersionAsync is not implemented for NuGetServerAPICalls.");
}
public override Task<FindResults> FindVersionGlobbingAsync(string packageName, VersionRange versionRange, bool includePrerelease, ResourceType type, bool getOnlyLatest, ConcurrentQueue<ErrorRecord> errorMsgs, ConcurrentQueue<string> warningMsgs, ConcurrentQueue<string> debugMsgs, ConcurrentQueue<string> verboseMsgs)
{
throw new NotImplementedException("FindVersionGlobbingAsync is not implemented for NuGetServerAPICalls.");
}
/// <summary>
/// Find method which allows for searching for all packages from a repository and returns latest version for each.
/// Examples: Search -Repository MyNuGetServer
/// API call:
/// - No prerelease: {repoUri}/api/v2/Search()?$filter=IsLatestVersion
/// </summary>
public override FindResults FindAll(bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindAll()");
errRecord = null;
List<string> responses = new List<string>();
int skip = 0;
string initialResponse = FindAllFromEndPoint(includePrerelease, skip, out errRecord);
if (errRecord != null)
{
_cmdletPassedIn.WriteDebug($"Error: {errRecord.Exception.Message}");
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(initialResponse);
int initialCount = GetCountFromResponse(initialResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
int count = initialCount / 6000;
// if more than 100 count, loop and add response to list
while (count > 0)
{
skip += 6000;
var tmpResponse = FindAllFromEndPoint(includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for packages with tag from a repository and returns latest version for each.
/// Examples: Search -Tag "JSON" -Repository PSGallery
/// API call:
/// - Include prerelease: {repoUri}/api/v2/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=tag:JSON&includePrerelease=true
/// </summary>
public override FindResults FindTags(string[] tags, bool includePrerelease, ResourceType _type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindTags()");
errRecord = null;
List<string> responses = new List<string>();
int skip = 0;
string initialResponse = FindTagFromEndpoint(tags, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(initialResponse);
int initialCount = GetCountFromResponse(initialResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
int count = initialCount / 100;
// if more than 100 count, loop and add response to list
while (count > 0)
{
// skip 100
skip += 100;
var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for all packages that have specified Command or DSCResource name.
/// </summary>
public override FindResults FindCommandOrDscResource(string[] tags, bool includePrerelease, bool isSearchingForCommands, out ErrorRecord errRecord)
{
errRecord = new ErrorRecord(
new InvalidOperationException($"Find by CommandName or DSCResource is not supported for the repository '{Repository.Name}'"),
"FindCommandOrDscResourceFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet"
/// API call:
/// - No prerelease: {repoUri}/api/v2/FindPackagesById()?id='PowerShellGet'
/// - Include prerelease: {repoUri}/api/v2/FindPackagesById()?id='PowerShellGet'
/// Implementation Note: Need to filter further for latest version (prerelease or non-prerelease depending on user preference)
/// </summary>
public override FindResults FindName(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindName()");
// This should return the latest stable version or the latest prerelease version (respectively)
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'&$filter=IsLatestVersion and substringof('PSModule', Tags) eq true
// Make sure to include quotations around the package name
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion");
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
filterBuilder.AddCriterion($"Id eq '{packageName}'");
var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrl, out errRecord);
return new FindResults(stringResponse: new string[]{ response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
public override Task<FindResults> FindNameAsync(string packageName, bool includePrerelease, ResourceType type, ConcurrentQueue<ErrorRecord> errorMsgs, ConcurrentQueue<string> warningMsgs, ConcurrentQueue<string> debugMsgs, ConcurrentQueue<string> verboseMsgs)
{
throw new NotImplementedException("FindNameAsync is not implemented for NuGetServerAPICalls.");
}
/// <summary>
/// Find method which allows for searching for single name and tag and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet" -Tag "Provider"
/// Implementation Note: Need to filter further for latest version (prerelease or non-prerelease depending on user preference)
/// </summary>
public override FindResults FindNameWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindNameWithTag()");
// This should return the latest stable version or the latest prerelease version (respectively)
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'&$filter=IsLatestVersion and substringof('PSModule', Tags) eq true
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
filterBuilder.AddCriterion($"Id eq '{packageName}'");
filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion");
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrl, out errRecord);
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*"
/// API call:
/// - No prerelease: {repoUri}/api/v2/Search()?$filter=IsLatestVersion&searchTerm='az*'
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbing(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindNameGlobbing()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindNameGlobbing(packageName, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(initialResponse);
// check count (regex) 425 ==> count/100 ~~> 4 calls
int initialCount = GetCountFromResponse(initialResponse, out errRecord); // count = 4
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
int count = initialCount / 100;
// if more than 100 count, loop and add response to list
while (count > 0)
{
// skip 100
skip += 100;
var tmpResponse = FindNameGlobbing(packageName, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and tag and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*" -Tag "Provider"
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbingWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindNameGlobbingWithTag()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindNameGlobbingWithTag(packageName, tags, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(initialResponse);
// check count (regex) 425 ==> count/100 ~~> 4 calls
int initialCount = GetCountFromResponse(initialResponse, out errRecord); // count = 4
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
int count = initialCount / 100;
// if more than 100 count, loop and add response to list
while (count > 0)
{
// skip 100
skip += 100;
var tmpResponse = FindNameGlobbingWithTag(packageName, tags, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with version range.
/// Name: no wildcard support
/// Version: supports wildcards
/// Examples: Search "PowerShellGet" "[3.0.0.0, 5.0.0.0]"
/// Search "PowerShellGet" "3.*"
/// API Call: {repoUri}/api/v2/FindPackagesById()?id='PowerShellGet'
/// Implementation note: Returns all versions, including prerelease ones. Later (in the API client side) we'll do filtering on the versions to satisfy what user provided.
/// </summary>
public override FindResults FindVersionGlobbing(string packageName, VersionRange versionRange, bool includePrerelease, ResourceType type, bool getOnlyLatest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindVersionGlobbing()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindVersionGlobbing(packageName, versionRange, includePrerelease, skip, getOnlyLatest, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(initialResponse);
if (!getOnlyLatest)
{
int initialCount = GetCountFromResponse(initialResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
int count = initialCount / 100;
while (count > 0)
{
// skip 100
skip += 100;
var tmpResponse = FindVersionGlobbing(packageName, versionRange, includePrerelease, skip, getOnlyLatest, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5"
/// API call: {repoUri}/api/v2/Packages(Id='PowerShellGet', Version='2.2.5')
/// </summary>
public override FindResults FindVersion(string packageName, string version, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindVersion()");
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='blah'&includePrerelease=false&$filter= NormalizedVersion eq '1.1.0' and substringof('PSModule', Tags) eq true
// Quotations around package name and version do not matter, same metadata gets returned.
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
filterBuilder.AddCriterion($"Id eq '{packageName}'");
filterBuilder.AddCriterion($"NormalizedVersion eq '{packageName}'");
var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrl, out errRecord);
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version and tag.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5" -Tag "Provider"
/// </summary>
public override FindResults FindVersionWithTag(string packageName, string version, string[] tags, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindVersionWithTag()");
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
filterBuilder.AddCriterion($"Id eq '{packageName}'");
filterBuilder.AddCriterion($"NormalizedVersion eq '{packageName}'");
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrl, out errRecord);
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType);
}
/** INSTALL APIS **/
/// <summary>
/// Installs a specific package.
/// User may request to install package with or without providing version (as seen in examples below), but prior to calling this method the package is located and package version determined.
/// Therefore, package version should not be null in this method.
/// Name: no wildcard support.
/// Examples: Install "PowerShellGet"
/// Install "PowerShellGet" -Version "3.0.0"
/// </summary>
public override Stream InstallPackage(string packageName, string packageVersion, bool includePrerelease, out ErrorRecord errRecord)
{
Stream results = new MemoryStream();
if (string.IsNullOrEmpty(packageVersion))
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException($"Package version could not be found for {packageName}"),
"PackageVersionNullOrEmptyError",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);
return results;
}
results = InstallVersion(packageName, packageVersion, out errRecord);
return results;
}
/// <summary>
/// Installs a specific package asynchronously.
/// User may request to install package with or without providing version (as seen in examples below), but prior to calling this method the package is located and package version determined.
/// Therefore, package version should not be null in this method.
/// Name: no wildcard support.
/// Examples: Install "PowerShellGet" -Version "3.5.0-alpha"
/// Install "PowerShellGet" -Version "3.0.0"
/// </summary>
public override Task<Stream> InstallPackageAsync(string packageName, string packageVersion, bool includePrerelease, ConcurrentQueue<ErrorRecord> errorMsgs, ConcurrentQueue<string> warningMsgs, ConcurrentQueue<string> debugMsgs, ConcurrentQueue<string> verboseMsgs)
{
throw new NotImplementedException("InstallPackageAsync is not implemented for NuGetServerAPICalls.");
}
/// <summary>
/// Helper method that makes the HTTP request for the NuGet server protocol url passed in for find APIs.
/// </summary>
private string HttpRequestCall(string requestUrl, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::HttpRequestCall()");
errRecord = null;
string response = string.Empty;
try
{
_cmdletPassedIn.WriteDebug($"Request url is: '{requestUrl}'");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
response = SendRequestAsync(request, _sessionClient).GetAwaiter().GetResult();
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFallFailure",
ErrorCategory.ConnectionError,
this);
}
catch (ArgumentNullException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFallFailure",
ErrorCategory.ConnectionError,
this);
}
catch (InvalidOperationException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFallFailure",
ErrorCategory.ConnectionError,
this);
}
if (string.IsNullOrEmpty(response))
{
_cmdletPassedIn.WriteDebug("Response is empty");
}
return response;
}
/// <summary>
/// Helper method that makes the HTTP request for the NuGet server protocol url passed in for install APIs.
/// </summary>
private HttpContent HttpRequestCallForContent(string requestUrl, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::HttpRequestCallForContent()");
errRecord = null;
HttpContent content = null;
try
{
_cmdletPassedIn.WriteDebug($"Request url is: '{requestUrl}'");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
content = SendRequestForContentAsync(request, _sessionClient).GetAwaiter().GetResult();
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.ConnectionError ,
this);
}
catch (ArgumentNullException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.InvalidData,
this);
}
catch (InvalidOperationException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.InvalidOperation,
this);
}
if (string.IsNullOrEmpty(content.ToString()))
{
_cmdletPassedIn.WriteDebug("Response is empty");
}
return content;
}
#endregion
#region Private Methods
/// <summary>
/// Helper method for string[] FindAll(string, PSRepositoryInfo, bool, bool, ResourceType, out string)
/// </summary>
private string FindAllFromEndPoint(bool includePrerelease, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindAllFromEndPoint()");
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string> {
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString() },
{ "$top", "6000" },
{ "$orderBy", "Id desc" },
});
var filterBuilder = queryBuilder.FilterBuilder;
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
} else {
filterBuilder.AddCriterion("IsLatestVersion");
}
var requestUrl = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrl, out errRecord);
}
/// <summary>
/// Helper method for string[] FindTag(string, PSRepositoryInfo, bool, bool, ResourceType, out string)
/// </summary>
private string FindTagFromEndpoint(string[] tags, bool includePrerelease, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindTagFromEndpoint()");
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string> {
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString() },
{ "$top", "6000" },
{ "$orderBy", "Id desc" },
});
var filterBuilder = queryBuilder.FilterBuilder;
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
} else {
filterBuilder.AddCriterion("IsLatestVersion");
}
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrl = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrl, out errRecord);
}
/// <summary>
/// Helper method for string[] FindNameGlobbing()
/// </summary>
private string FindNameGlobbing(string packageName, bool includePrerelease, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindNameGlobbing()");
// https://www.powershellgallery.com/api/v2/Search()?$filter=endswith(Id, 'Get') and startswith(Id, 'PowerShell') and IsLatestVersion (stable)
// https://www.powershellgallery.com/api/v2/Search()?$filter=endswith(Id, 'Get') and IsAbsoluteLatestVersion&includePrerelease=true
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string> {
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString() },
{ "$top", "100" },
{ "$orderBy", "NormalizedVersion desc" },
});
var filterBuilder = queryBuilder.FilterBuilder;
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
} else {
filterBuilder.AddCriterion("IsLatestVersion");
}
var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries);
if (names.Length == 0)
{
errRecord = new ErrorRecord(
new ArgumentException("-Name '*' for NuGet.Server hosted feed repository is not supported"),
"FindNameGlobbingFailure",
ErrorCategory.InvalidArgument,
this);
return string.Empty;
}
if (names.Length == 1)
{
if (packageName.StartsWith("*") && packageName.EndsWith("*"))
{
// *get*
filterBuilder.AddCriterion($"substringof('{names[0]}', Id)");
}
else if (packageName.EndsWith("*"))
{
// PowerShell*
filterBuilder.AddCriterion($"startswith(Id, '{names[0]}')");
}
else
{
// *ShellGet
filterBuilder.AddCriterion($"endswith(Id, '{names[0]}')");
}
}
else if (names.Length == 2 && !packageName.StartsWith("*") && !packageName.EndsWith("*"))
{
// *pow*get*
// pow*get -> only support this
// pow*get*
// *pow*get
filterBuilder.AddCriterion($"startswith(Id, '{names[0]}') and endswith(Id, '{names[1]}')");
}
else
{
errRecord = new ErrorRecord(
new ArgumentException("-Name with wildcards is only supported for scenarios similar to the following examples: PowerShell*, *ShellGet, *Shell*."),
"FindNameGlobbingFailure",
ErrorCategory.InvalidArgument,
this);
return string.Empty;
}
var requestUrl = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrl, out errRecord);
}
/// <summary>
/// Helper method for string[] FindNameGlobbingWithTag()
/// </summary>
private string FindNameGlobbingWithTag(string packageName, string[] tags, bool includePrerelease, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindNameGlobbingWithTag()");
// https://www.powershellgallery.com/api/v2/Search()?$filter=endswith(Id, 'Get') and startswith(Id, 'PowerShell') and IsLatestVersion (stable)
// https://www.powershellgallery.com/api/v2/Search()?$filter=endswith(Id, 'Get') and IsAbsoluteLatestVersion&includePrerelease=true
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string> {
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString() },
{ "$top", "100" },
{ "$orderBy", "Id desc" },
});
var filterBuilder = queryBuilder.FilterBuilder;
if (includePrerelease) {
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
} else {
filterBuilder.AddCriterion("IsLatestVersion");
}
var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries);
if (names.Length == 0)
{
errRecord = new ErrorRecord(
new ArgumentException("-Name '*' for NuGet.Server hosted feed repository is not supported"),
"FindNameGlobbingFailure",
ErrorCategory.InvalidArgument,
this);
return string.Empty;
}
if (names.Length == 1)
{
if (packageName.StartsWith("*") && packageName.EndsWith("*"))
{
// *get*
filterBuilder.AddCriterion($"substringof('{names[0]}', Id)");
}
else if (packageName.EndsWith("*"))
{
// PowerShell*
filterBuilder.AddCriterion($"startswith(Id, '{names[0]}')");
}
else
{
// *ShellGet
filterBuilder.AddCriterion($"endswith(Id, '{names[0]}')");
}
}
else if (names.Length == 2 && !packageName.StartsWith("*") && !packageName.EndsWith("*"))
{
// *pow*get*
// pow*get -> only support this
// pow*get*
// *pow*get
filterBuilder.AddCriterion($"startswith(Id, '{names[0]}') and endswith(Id, '{names[1]}')");
}
else
{
errRecord = new ErrorRecord(
new ArgumentException("-Name with wildcards is only supported for scenarios similar to the following examples: PowerShell*, *ShellGet, *Shell*."),
"FindNameGlobbing",
ErrorCategory.InvalidArgument,
this);
return string.Empty;
}
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrl = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrl, out errRecord);
}
/// <summary>
/// Helper method for string[] FindVersionGlobbing()
/// </summary>
private string FindVersionGlobbing(string packageName, VersionRange versionRange, bool includePrerelease, int skip, bool getOnlyLatest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::FindVersionGlobbing()");
//https://www.powershellgallery.com/api/v2//FindPackagesById()?id='blah'&includePrerelease=false&$filter= NormalizedVersion gt '1.0.0' and NormalizedVersion lt '2.2.5' and substringof('PSModule', Tags) eq true
//https://www.powershellgallery.com/api/v2//FindPackagesById()?id='PowerShellGet'&includePrerelease=false&$filter= NormalizedVersion gt '1.1.1' and NormalizedVersion lt '2.2.5'
// NormalizedVersion doesn't include trailing zeroes
// Notes: this could allow us to take a version range (i.e (2.0.0, 3.0.0.0]) and deconstruct it and add options to the Filter for Version to describe that range
// will need to filter additionally, if IncludePrerelease=false, by default we get stable + prerelease both back
// Current bug: Find PSGet -Version "2.0.*" -> https://www.powershellgallery.com/api/v2//FindPackagesById()?id='PowerShellGet'&includePrerelease=false&$filter= Version gt '2.0.*' and Version lt '2.1'
// Make sure to include quotations around the package name
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string> {
{ "id", $"'{packageName}'" },
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString() },
{ "$top", getOnlyLatest ? "1" : "100" },
{ "$orderBy", "NormalizedVersion desc" },
});
var filterBuilder = queryBuilder.FilterBuilder;
//and IsPrerelease eq false
// ex:
// (2.0.0, 3.0.0)
// $filter= NVersion gt '2.0.0' and NVersion lt '3.0.0'
// [2.0.0, 3.0.0]
// $filter= NVersion ge '2.0.0' and NVersion le '3.0.0'
// [2.0.0, 3.0.0)
// $filter= NVersion ge '2.0.0' and NVersion lt '3.0.0'
// (2.0.0, 3.0.0]
// $filter= NVersion gt '2.0.0' and NVersion le '3.0.0'
// [, 2.0.0]
// $filter= NVersion le '2.0.0'
string format = "NormalizedVersion {0} {1}";
string minPart = String.Empty;
string maxPart = String.Empty;
if (versionRange.MinVersion != null)
{
string operation = versionRange.IsMinInclusive ? "ge" : "gt";
minPart = String.Format(format, operation, $"'{versionRange.MinVersion.ToNormalizedString()}'");
}
if (versionRange.MaxVersion != null)
{
string operation = versionRange.IsMaxInclusive ? "le" : "lt";
maxPart = String.Format(format, operation, $"'{versionRange.MaxVersion.ToNormalizedString()}'");
}
string versionFilterParts = String.Empty;
if (!String.IsNullOrEmpty(minPart))
{
filterBuilder.AddCriterion(minPart);
}
if (!String.IsNullOrEmpty(maxPart))
{
filterBuilder.AddCriterion(maxPart);
}
if (!includePrerelease) {
filterBuilder.AddCriterion("IsPrerelease eq false");
}
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
filterBuilder.AddCriterion($"Id eq '{packageName}'");
var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrl, out errRecord);
}
/// <summary>
/// Installs specific package.
/// Name: no wildcard support.
/// Examples: Install "PowerShellGet"
/// Implementation Note: {repoUri}/Packages(Id='test_local_mod')/Download
/// if prerelease, call into InstallVersion instead.
/// </summary>
private Stream InstallName(string packageName, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::InstallName()");
var requestUrl = $"{Repository.Uri}/Packages/(Id='{packageName}')/Download";
var response = HttpRequestCallForContent(requestUrl, out errRecord);
if (response is null)
{
errRecord = new ErrorRecord(
new Exception($"No content was returned by repository '{Repository.Name}'"),
"InstallFailureContentNullNuGetServer",
ErrorCategory.InvalidResult,
this);
return null;
}
return response.ReadAsStreamAsync().Result;
}
/// <summary>
/// Installs package with specific name and version.
/// Name: no wildcard support.
/// Version: no wildcard support.
/// Examples: Install "PowerShellGet" -Version "3.0.0.0"
/// Install "PowerShellGet" -Version "3.0.0-beta16"
/// API Call: {repoUri}/Packages(Id='Castle.Core',Version='5.1.1')/Download
/// </summary>
private Stream InstallVersion(string packageName, string version, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::InstallVersion()");
var requestUrl = $"{Repository.Uri}/Packages(Id='{packageName}',Version='{version}')/Download";
var response = HttpRequestCallForContent(requestUrl, out errRecord);
if (response is null)
{
errRecord = new ErrorRecord(
new Exception($"No content was returned by repository '{Repository.Name}'"),
"InstallFailureContentNullNuGetServer",
ErrorCategory.InvalidResult,
this);
return null;
}
return response.ReadAsStreamAsync().Result;
}
/// <summary>
/// Helper method that makes gets 'count' property from http response string.
/// The count property is used to determine the number of total results found (for pagination).
/// </summary>
public int GetCountFromResponse(string httpResponse, out ErrorRecord errRecord)
{
errRecord = null;
int count = 0;
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(httpResponse);
}
catch (XmlException e)
{
errRecord = new ErrorRecord(
exception: e,
"GetCountFromResponse",
ErrorCategory.InvalidData,
this);
}
if (errRecord != null)
{
return count;
}
XmlNodeList elemList = doc.GetElementsByTagName("m:count");
if (elemList.Count > 0)
{
XmlNode node = elemList[0];
count = int.Parse(node.InnerText);
}
return count;
}
/// <summary>
/// Helper method called by HttpRequestCall() that makes the HTTP request for string response.
/// </summary>
public static async Task<string> SendRequestAsync(HttpRequestMessage message, HttpClient s_client)
{
string errMsg = "Error occurred while trying to retrieve response: ";
try
{
HttpResponseMessage response = await s_client.SendAsync(message);
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
catch (HttpRequestException e)
{
throw new HttpRequestException(errMsg + e.Message);
}
catch (ArgumentNullException e)
{
throw new ArgumentNullException(errMsg + e.Message);
}
catch (InvalidOperationException e)
{
throw new InvalidOperationException(errMsg + e.Message);