-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathPublishHelper.cs
More file actions
1601 lines (1404 loc) · 69.7 KB
/
PublishHelper.cs
File metadata and controls
1601 lines (1404 loc) · 69.7 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
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Packaging;
using NuGet.Versioning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Management.Automation;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Xml;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
internal class PublishHelper
{
#region Enums
internal enum CallerCmdlet
{
PublishPSResource,
CompressPSResource
}
#endregion
#region Members
private readonly CallerCmdlet _callerCmdlet;
private readonly PSCmdlet _cmdletPassedIn;
private readonly string _cmdOperation;
private readonly string Path;
private string DestinationPath;
private string resolvedPath;
private CancellationToken _cancellationToken;
private NuGetVersion _pkgVersion;
private string _pkgName;
private static char[] _PathSeparators = new[] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar };
public const string PSDataFileExt = ".psd1";
public const string PSScriptFileExt = ".ps1";
public const string NupkgFileExt = ".nupkg";
private const string PSScriptInfoCommentString = "<#PSScriptInfo";
private string pathToScriptFileToPublish = string.Empty;
private string pathToModuleManifestToPublish = string.Empty;
private string pathToModuleDirToPublish = string.Empty;
private string pathToNupkgToPublish = string.Empty;
private ResourceType resourceType = ResourceType.None;
string userAgentString = UserAgentInfo.UserAgentString();
private bool _isNupkgPathSpecified = false;
private Hashtable dependencies;
private Hashtable parsedMetadata;
private PSCredential Credential;
private string outputNupkgDir;
private string ApiKey;
private bool SkipModuleManifestValidate = false;
private string outputDir = string.Empty;
internal bool ScriptError = false;
internal bool ShouldProcess = true;
internal bool PassThru = false;
#endregion
#region Constructors
internal PublishHelper(PSCmdlet cmdlet, string path, string destinationPath, bool passThru, bool skipModuleManifestValidate)
{
_callerCmdlet = CallerCmdlet.CompressPSResource;
_cmdOperation = "Compress";
_cmdletPassedIn = cmdlet;
Path = path;
DestinationPath = destinationPath;
PassThru = passThru;
SkipModuleManifestValidate = skipModuleManifestValidate;
outputDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
outputNupkgDir = destinationPath;
}
internal PublishHelper(PSCmdlet cmdlet,
PSCredential credential,
string apiKey,
string path,
string destinationPath,
bool skipModuleManifestValidate,
CancellationToken cancellationToken,
bool isNupkgPathSpecified)
{
_callerCmdlet = CallerCmdlet.PublishPSResource;
_cmdOperation = "Publish";
_cmdletPassedIn = cmdlet;
Credential = credential;
ApiKey = apiKey;
Path = path;
DestinationPath = destinationPath;
SkipModuleManifestValidate = skipModuleManifestValidate;
_cancellationToken = cancellationToken;
_isNupkgPathSpecified = isNupkgPathSpecified;
outputDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
outputNupkgDir = System.IO.Path.Combine(outputDir, "nupkg");
}
#endregion
#region Internal Methods
internal void PackResource()
{
// Returns the name of the file or the name of the directory, depending on path
if (!_cmdletPassedIn.ShouldProcess(string.Format("'{0}' from the machine", resolvedPath)))
{
_cmdletPassedIn.WriteVerbose("ShouldProcess is set to false.");
ShouldProcess = false;
return;
}
parsedMetadata = new Hashtable(StringComparer.OrdinalIgnoreCase);
if (resourceType == ResourceType.Script)
{
if (!PSScriptFileInfo.TryTestPSScriptFileInfo(
scriptFileInfoPath: pathToScriptFileToPublish,
parsedScript: out PSScriptFileInfo scriptToPublish,
out ErrorRecord[] errors,
out string[] _
))
{
foreach (ErrorRecord error in errors)
{
_cmdletPassedIn.WriteError(error);
}
ScriptError = true;
return;
}
parsedMetadata = scriptToPublish.ToHashtable();
_pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToScriptFileToPublish);
}
else
{
if (!string.IsNullOrEmpty(pathToModuleManifestToPublish))
{
_pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToModuleManifestToPublish);
}
else
{
// Search for module manifest
foreach (FileInfo file in new DirectoryInfo(pathToModuleDirToPublish).EnumerateFiles())
{
if (file.Name.EndsWith(PSDataFileExt, StringComparison.OrdinalIgnoreCase))
{
pathToModuleManifestToPublish = file.FullName;
_pkgName = System.IO.Path.GetFileNameWithoutExtension(file.Name);
break;
}
}
}
// Validate that there's a module manifest
if (!File.Exists(pathToModuleManifestToPublish))
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"No file with a .psd1 extension was found in '{pathToModuleManifestToPublish}'. Please specify a path to a valid module manifest."),
"moduleManifestNotFound",
ErrorCategory.ObjectNotFound,
this));
return;
}
// The Test-ModuleManifest currently cannot process UNC paths. Disabling verification for now.
if ((new Uri(pathToModuleManifestToPublish)).IsUnc)
SkipModuleManifestValidate = true;
// Validate that the module manifest has correct data
if (!SkipModuleManifestValidate &&
!Utils.ValidateModuleManifest(pathToModuleManifestToPublish, out string errorMsg))
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(errorMsg),
"InvalidModuleManifest",
ErrorCategory.InvalidOperation,
this));
}
if (!Utils.TryReadManifestFile(
manifestFilePath: pathToModuleManifestToPublish,
manifestInfo: out parsedMetadata,
error: out Exception manifestReadError))
{
_cmdletPassedIn.WriteError(new ErrorRecord(
manifestReadError,
"ManifestFileReadParseForContainerRegistryPublishError",
ErrorCategory.ReadError,
this));
return;
}
}
// Create a temp folder to push the nupkg to and delete it later
try
{
Directory.CreateDirectory(outputDir);
}
catch (Exception e)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException(e.Message),
"ErrorCreatingTempDir",
ErrorCategory.InvalidData,
this));
return;
}
try
{
string nuspec = string.Empty;
// Create a nuspec
try
{
nuspec = CreateNuspec(
outputDir: outputDir,
filePath: (resourceType == ResourceType.Script) ? pathToScriptFileToPublish : pathToModuleManifestToPublish,
parsedMetadataHash: parsedMetadata,
requiredModules: out dependencies);
}
catch (Exception e)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"Nuspec creation failed: {e.Message}"),
"NuspecCreationFailed",
ErrorCategory.ObjectNotFound,
this));
return;
}
if (string.IsNullOrEmpty(nuspec))
{
// nuspec creation failed.
_cmdletPassedIn.WriteVerbose("Nuspec creation failed.");
return;
}
if (resourceType == ResourceType.Script)
{
// copy the script file to the temp directory
File.Copy(pathToScriptFileToPublish, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true);
}
else
{
try
{
// If path is pointing to a file, get the parent directory, otherwise assumption is that path is pointing to the root directory
string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? System.IO.Path.GetDirectoryName(pathToModuleManifestToPublish) : pathToModuleDirToPublish;
// Create subdirectory structure in temp folder
foreach (string dir in Directory.GetDirectories(rootModuleDir, "*", SearchOption.AllDirectories))
{
var dirName = dir.Substring(rootModuleDir.Length).Trim(_PathSeparators);
Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirName));
}
// Copy files over to temp folder
foreach (string fileNamePath in Directory.GetFiles(rootModuleDir, "*", SearchOption.AllDirectories))
{
var fileName = fileNamePath.Substring(rootModuleDir.Length).Trim(_PathSeparators);
var newFilePath = System.IO.Path.Combine(outputDir, fileName);
// The user may have a .nuspec defined in the module directory
// If that's the case, we will not use that file and use the .nuspec that is generated via PSGet
// The .nuspec that is already in in the output directory is the one that was generated via the CreateNuspec method
if (!File.Exists(newFilePath))
{
File.Copy(fileNamePath, newFilePath);
}
}
}
catch (Exception e)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new ArgumentException("Error occurred while creating directory to publish: " + e.Message),
"ErrorCreatingDirectoryToPublish",
ErrorCategory.InvalidOperation,
this));
}
}
if (_callerCmdlet == CallerCmdlet.CompressPSResource)
{
outputNupkgDir = DestinationPath;
}
// pack into .nupkg
if (!PackNupkg(outputDir, outputNupkgDir, nuspec, out ErrorRecord packNupkgError))
{
_cmdletPassedIn.WriteError(packNupkgError);
// exit out of processing
return;
}
}
catch (Exception e)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
e,
$"{this.GetType()}Error",
ErrorCategory.NotSpecified,
this));
}
finally
{
if(_callerCmdlet == CallerCmdlet.CompressPSResource)
{
_cmdletPassedIn.WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir));
Utils.DeleteDirectory(outputDir);
}
}
}
internal void PushResource(string Repository, string modulePrefix, bool SkipDependenciesCheck, NetworkCredential _networkCredential)
{
try
{
PSRepositoryInfo repository = RepositorySettings.Read(new[] { Repository }, out _).FirstOrDefault();
// Find repository
if (repository == null)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"The resource repository '{Repository}' is not a registered. Please run 'Register-PSResourceRepository' in order to publish to this repository."),
"RepositoryNotFound",
ErrorCategory.ObjectNotFound,
this));
return;
}
else if (repository.Uri.Scheme == Uri.UriSchemeFile && !repository.Uri.IsUnc && !Directory.Exists(repository.Uri.LocalPath))
{
// this check to ensure valid local path is not for UNC paths (which are server based, instead of Drive based)
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"The repository '{repository.Name}' with uri: '{repository.Uri.AbsoluteUri}' is not a valid folder path which exists. If providing a file based repository, provide a repository with a path that exists."),
"repositoryPathDoesNotExist",
ErrorCategory.ObjectNotFound,
this));
return;
}
bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repository.Uri);
if (!isAllowed)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new PSInvalidOperationException($"Repository '{repository.Name}' is not allowed by Group Policy."),
"RepositoryNotAllowedByGroupPolicy",
ErrorCategory.PermissionDenied,
this));
return;
}
if (repository.IsMARRepository())
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new PSInvalidOperationException($"Repository '{repository.Name}' is a MAR repository and cannot be published to."),
"MARRepositoryPublishError",
ErrorCategory.PermissionDenied,
this));
return;
}
// Set network credentials via passed in credentials, AzArtifacts CredentialProvider, or SecretManagement.
var networkCredential = repository.SetNetworkCredentials(_networkCredential, _cmdletPassedIn);
// Check if dependencies already exist within the repo if:
// 1) the resource to publish has dependencies and
// 2) the -SkipDependenciesCheck flag is not passed in
if (dependencies != null && !SkipDependenciesCheck)
{
// If error gets thrown, exit process record
if (!CheckDependenciesExist(dependencies, repository.Name, networkCredential))
{
return;
}
}
// If -DestinationPath is specified then also publish the .nupkg there
if (!string.IsNullOrWhiteSpace(DestinationPath))
{
if (!Directory.Exists(DestinationPath))
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"Destination path does not exist: '{DestinationPath}'"),
"InvalidDestinationPath",
ErrorCategory.InvalidArgument,
this));
return;
}
if (!_isNupkgPathSpecified)
{
try
{
var nupkgName = _pkgName + "." + _pkgVersion.ToNormalizedString() + ".nupkg";
var sourceFilePath = System.IO.Path.Combine(outputNupkgDir, nupkgName);
var destinationFilePath = System.IO.Path.Combine(DestinationPath, nupkgName);
if (!File.Exists(destinationFilePath))
{
File.Copy(sourceFilePath, destinationFilePath);
}
}
catch (Exception e)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException($"Error moving .nupkg into destination path '{DestinationPath}' due to: '{e.Message}'."),
"ErrorMovingNupkg",
ErrorCategory.NotSpecified,
this));
// exit process record
return;
}
}
}
string repositoryUri = repository.Uri.AbsoluteUri;
if (repository.ApiVersion == PSRepositoryInfo.APIVersion.ContainerRegistry)
{
ContainerRegistryServerAPICalls containerRegistryServer = new ContainerRegistryServerAPICalls(repository, _cmdletPassedIn, networkCredential, userAgentString);
if (_isNupkgPathSpecified)
{
// copy the .nupkg to a temp path (outputNupkgDir field) as we don't want to tamper with the original, possibly signed, .nupkg file
string copiedNupkgFilePath = CopyNupkgFileToTempPath(nupkgFilePath: Path, errRecord: out ErrorRecord copyErrRecord);
if (copyErrRecord != null)
{
_cmdletPassedIn.WriteError(copyErrRecord);
return;
}
// get package info (name, version, metadata hashtable) from the copied .nupkg package and then populate appropriate fields (_pkgName, _pkgVersion, parsedMetadata)
GetPackageInfoFromNupkg(nupkgFilePath: copiedNupkgFilePath, errRecord: out ErrorRecord pkgInfoErrRecord);
if (pkgInfoErrRecord != null)
{
_cmdletPassedIn.WriteError(pkgInfoErrRecord);
return;
}
}
if (!containerRegistryServer.PushNupkgContainerRegistry(outputNupkgDir, _pkgName, modulePrefix, _pkgVersion, resourceType, parsedMetadata, dependencies, _isNupkgPathSpecified, Path, out ErrorRecord pushNupkgContainerRegistryError))
{
_cmdletPassedIn.WriteError(pushNupkgContainerRegistryError);
return;
}
}
else
{
if(_isNupkgPathSpecified)
{
outputNupkgDir = pathToNupkgToPublish;
}
// This call does not throw any exceptions, but it will write unsuccessful responses to the console
if (!PushNupkg(outputNupkgDir, repository.Name, repository.Uri.ToString(), networkCredential, out ErrorRecord pushNupkgError))
{
_cmdletPassedIn.WriteError(pushNupkgError);
// exit out of processing
return;
}
}
}
catch (Exception e)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
e,
"PublishPSResourceError",
ErrorCategory.NotSpecified,
this));
}
finally
{
// For scenarios such as Publish-PSResource -NupkgPath -Repository <non-container registry repository>, the outputNupkgDir will be set to NupkgPath path, and a temp outputDir folder will not have been created and thus doesn't need to attempt to be deleted
if (Directory.Exists(outputDir))
{
_cmdletPassedIn.WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir));
Utils.DeleteDirectory(outputDir);
}
}
}
internal void CheckAllParameterPaths()
{
try
{
resolvedPath = _cmdletPassedIn.GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider).First();
}
catch (MethodInvocationException)
{
// path does not exist
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new ArgumentException($"The path to the resource to {_cmdOperation.ToLower()} does not exist, point to an existing path or file of the module or script to {_cmdOperation.ToLower()}."),
"SourcePathDoesNotExist",
ErrorCategory.InvalidArgument,
this));
}
// Condition 1: path is to the root directory of the module to be published
// Condition 2: path is to the .psd1 or .ps1 of the module/script to be published
if (string.IsNullOrEmpty(resolvedPath))
{
// unsupported file path
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new ArgumentException($"The path to the resource to {_cmdOperation.ToLower()} is not in the correct format or does not exist. Please provide the path of the root module " +
$"(i.e. './<ModuleTo{_cmdOperation}>/') or the path to the .psd1 (i.e. './<ModuleTo{_cmdOperation}>/<ModuleTo{_cmdOperation}>.psd1')."),
$"Invalid{_cmdOperation}Path",
ErrorCategory.InvalidArgument,
this));
}
else if (Directory.Exists(resolvedPath))
{
pathToModuleDirToPublish = resolvedPath;
resourceType = ResourceType.Module;
}
else if (resolvedPath.EndsWith(PSDataFileExt, StringComparison.OrdinalIgnoreCase))
{
pathToModuleManifestToPublish = resolvedPath;
resourceType = ResourceType.Module;
}
else if (resolvedPath.EndsWith(PSScriptFileExt, StringComparison.OrdinalIgnoreCase))
{
pathToScriptFileToPublish = resolvedPath;
resourceType = ResourceType.Script;
}
else if (resolvedPath.EndsWith(NupkgFileExt, StringComparison.OrdinalIgnoreCase) && _isNupkgPathSpecified)
{
pathToNupkgToPublish = resolvedPath;
resourceType = ResourceType.Nupkg;
}
else
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new ArgumentException($"The {_cmdOperation.ToLower()} path provided, '{resolvedPath}', is not a valid. Please provide a path to the root module " +
$"(i.e. './<ModuleTo{_cmdOperation}>/') or path to the .psd1 (i.e. './<ModuleTo{_cmdOperation}>/<ModuleTo{_cmdOperation}>.psd1')."),
$"Invalid{_cmdOperation}Path",
ErrorCategory.InvalidArgument,
this));
}
if (!String.IsNullOrEmpty(DestinationPath))
{
string resolvedDestinationPath = _cmdletPassedIn.GetResolvedProviderPathFromPSPath(DestinationPath, out ProviderInfo provider).First();
if (Directory.Exists(resolvedDestinationPath))
{
DestinationPath = resolvedDestinationPath;
}
else
{
try
{
Directory.CreateDirectory(resolvedDestinationPath);
}
catch (Exception e)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new ArgumentException($"Destination path does not exist and cannot be created: {e.Message}"),
"InvalidDestinationPath",
ErrorCategory.InvalidArgument,
this));
}
}
}
}
#endregion
#region Private Methods
private bool PackNupkg(string outputDir, string outputNupkgDir, string nuspecFile, out ErrorRecord error)
{
_cmdletPassedIn.WriteDebug("In PublishHelper::PackNupkg()");
// Pack the module or script into a nupkg given a nuspec.
var builder = new PackageBuilder();
try
{
var runner = new PackCommandRunner(
new PackArgs
{
CurrentDirectory = outputDir,
OutputDirectory = outputNupkgDir,
Path = nuspecFile,
Exclude = System.Array.Empty<string>(),
Symbols = false,
Logger = NullLogger.Instance,
NoDefaultExcludes = true
},
MSBuildProjectFactory.ProjectCreator,
builder);
bool success = runner.RunPackageBuild();
if (success)
{
if (PassThru)
{
var nupkgPath = System.IO.Path.Combine(outputNupkgDir, _pkgName + "." + _pkgVersion.ToNormalizedString() + ".nupkg");
_cmdletPassedIn.WriteObject(new FileInfo(nupkgPath));
}
_cmdletPassedIn.WriteVerbose("Successfully packed the resource into a .nupkg");
}
else
{
error = new ErrorRecord(
new InvalidOperationException("Not able to successfully pack the resource into a .nupkg"),
"failedToPackIntoNupkg",
ErrorCategory.ObjectNotFound,
this);
return false;
}
}
catch (Exception e)
{
error = new ErrorRecord(
new ArgumentException($"Unexpected error packing into .nupkg: '{e.Message}'."),
"ErrorPackingIntoNupkg",
ErrorCategory.NotSpecified,
this);
// exit process record
return false;
}
error = null;
return true;
}
private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, NetworkCredential networkCredential, out ErrorRecord error)
{
_cmdletPassedIn.WriteDebug("In PublishPSResource::PushNupkg()");
string fullNupkgFile;
if (_isNupkgPathSpecified)
{
fullNupkgFile = outputNupkgDir;
}
else
{
// Push the nupkg to the appropriate repository
// Pkg version is parsed from .ps1 file or .psd1 file
fullNupkgFile = System.IO.Path.Combine(outputNupkgDir, _pkgName + "." + _pkgVersion.ToNormalizedString() + ".nupkg");
}
// The PSGallery uses the v2 protocol still and publishes to a slightly different endpoint:
// "https://www.powershellgallery.com/api/v2/package"
// Until the PSGallery is moved onto the NuGet v3 server protocol, we'll modify the repository uri
// to accommodate for the appropriate publish location.
string publishLocation = repoUri.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoUri + "/package" : repoUri;
var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null);
var success = false;
var sourceProvider = new PackageSourceProvider(settings);
if (Credential != null || networkCredential != null)
{
InjectCredentialsToSettings(settings, sourceProvider, publishLocation, networkCredential);
}
try
{
PushRunner.Run(
settings: Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null),
sourceProvider: sourceProvider,
packagePaths: new List<string> { fullNupkgFile },
source: publishLocation,
apiKey: ApiKey,
symbolSource: null,
symbolApiKey: null,
timeoutSeconds: 0,
disableBuffering: false,
noSymbols: false,
noServiceEndpoint: false, // enable server endpoint
skipDuplicate: false, // if true-- if a package and version already exists, skip it and continue with the next package in the push, if any.
logger: NullLogger.Instance // nuget logger
).GetAwaiter().GetResult();
}
catch (HttpRequestException e)
{
_cmdletPassedIn.WriteVerbose(string.Format("Not able to publish resource to '{0}'", repoUri));
// look in PS repo for how httpRequestExceptions are handled
// Unfortunately there is no response message are no status codes provided with the exception and no
var ex = new ArgumentException(String.Format("Repository '{0}': {1}", repoName, e.Message));
if (e.Message.Contains("400"))
{
if (e.Message.Contains("Api"))
{
// For ADO repositories, public and private, when ApiKey is not provided.
error = new ErrorRecord(
new ArgumentException($"Repository '{repoName}': Please try running again with the -ApiKey parameter and specific API key for the repository specified. For Azure Devops repository, set this to an arbitrary value, for example '-ApiKey AzureDevOps'"),
"400ApiKeyError",
ErrorCategory.AuthenticationError,
this);
}
else
{
error = new ErrorRecord(
ex,
"400Error",
ErrorCategory.PermissionDenied,
this);
}
}
else if (e.Message.Contains("401"))
{
if (e.Message.Contains("API"))
{
// For PSGallery when ApiKey is not provided.
error = new ErrorRecord(
new ArgumentException($"Could not publish to repository '{repoName}'. Please try running again with the -ApiKey parameter and the API key for the repository specified. Exception: '{e.Message}'"),
"401ApiKeyError",
ErrorCategory.AuthenticationError,
this);
}
else
{
// For ADO repository feeds that are public feeds, when the credentials are incorrect.
error = new ErrorRecord(new ArgumentException($"Could not publish to repository '{repoName}'. The Credential provided was incorrect. Exception: '{e.Message}'"),
"401Error",
ErrorCategory.PermissionDenied,
this); ;
}
}
else if (e.Message.Contains("403"))
{
if (repoUri.Contains("myget.org"))
{
// For myGet.org repository feeds when the ApiKey is missing or incorrect.
error = new ErrorRecord(
new ArgumentException($"Could not publish to repository '{repoName}'. The ApiKey provided is incorrect or missing. Please try running again with the -ApiKey parameter and correct API key value for the repository. Exception: '{e.Message}'"),
"403Error",
ErrorCategory.PermissionDenied,
this);
}
else if (repoUri.Contains(".jfrog.io"))
{
// For JFrog Artifactory repository feeds when the ApiKey is provided, whether correct or incorrect, as JFrog does not require -ApiKey (but does require ApiKey to be present as password to -Credential).
error = new ErrorRecord(
new ArgumentException($"Could not publish to repository '{repoName}'. The ApiKey provided is not needed for JFrog Artifactory. Please try running again without the -ApiKey parameter but ensure that -Credential is provided with ApiKey as password. Exception: '{e.Message}'"),
"403Error",
ErrorCategory.PermissionDenied,
this);
}
else
{
error = new ErrorRecord(
ex,
"403Error",
ErrorCategory.PermissionDenied,
this);
}
}
else if (e.Message.Contains("409"))
{
error = new ErrorRecord(
ex,
"409Error",
ErrorCategory.PermissionDenied, this);
}
else
{
error = new ErrorRecord(
ex,
"HTTPRequestError",
ErrorCategory.PermissionDenied,
this);
}
return success;
}
catch (NuGet.Protocol.Core.Types.FatalProtocolException e)
{
// for ADO repository feeds that are private feeds the error thrown is different and the 401 is in the inner exception message
if (e.InnerException.Message.Contains("401"))
{
error = new ErrorRecord(
new ArgumentException($"Could not publish to repository '{repoName}'. The Credential provided was incorrect. Exception '{e.InnerException.Message}'"),
"401FatalProtocolError",
ErrorCategory.AuthenticationError,
this);
}
else
{
error = new ErrorRecord(
new ArgumentException($"Repository '{repoName}': {e.InnerException.Message}"),
"ProtocolFailError",
ErrorCategory.ProtocolError,
this);
}
return success;
}
catch (Exception e)
{
_cmdletPassedIn.WriteVerbose($"Not able to publish resource to '{repoUri}'");
error = new ErrorRecord(
new ArgumentException(e.Message),
"PushNupkgError",
ErrorCategory.InvalidResult,
this);
return success;
}
_cmdletPassedIn.WriteVerbose(string.Format("Successfully published the resource to '{0}'", repoUri));
error = null;
success = true;
return success;
}
private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvider sourceProvider, string source, NetworkCredential networkCredential)
{
_cmdletPassedIn.WriteDebug("In PublishPSResource::InjectCredentialsToSettings()");
if (Credential == null && networkCredential == null)
{
return;
}
var packageSource = sourceProvider.LoadPackageSources().FirstOrDefault(s => s.Source == source);
if (packageSource != null)
{
if (!packageSource.IsEnabled)
{
packageSource.IsEnabled = true;
}
}
var networkCred = Credential == null ? networkCredential : Credential.GetNetworkCredential();
string key;
if (packageSource == null)
{
key = "_" + Guid.NewGuid().ToString().Replace("-", "");
settings.AddOrUpdate(
ConfigurationConstants.PackageSources,
new SourceItem(key, source));
}
else
{
key = packageSource.Name;
}
settings.AddOrUpdate(
ConfigurationConstants.CredentialsSectionName,
new CredentialsItem(
key,
networkCred.UserName,
networkCred.Password,
isPasswordClearText: true,
String.Empty));
}
private string CreateNuspec(
string outputDir,
string filePath,
Hashtable parsedMetadataHash,
out Hashtable requiredModules)
{
_cmdletPassedIn.WriteDebug("In PublishHelper::CreateNuspec()");
bool isModule = resourceType != ResourceType.Script;
requiredModules = new Hashtable();
if (parsedMetadataHash == null || parsedMetadataHash.Count == 0)
{
_cmdletPassedIn.WriteError(new ErrorRecord(new ArgumentException("Hashtable provided with package metadata was null or empty"),
"PackageMetadataHashtableNullOrEmptyError",
ErrorCategory.ReadError,
this));
return string.Empty;
}
// now we have parsedMetadatahash to fill out the nuspec information
var nameSpaceUri = "http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd";
var doc = new XmlDocument();
// xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmlDeclaration, root);
// create top-level elements
XmlElement packageElement = doc.CreateElement("package", nameSpaceUri);
XmlElement metadataElement = doc.CreateElement("metadata", nameSpaceUri);
Dictionary<string, string> metadataElementsDictionary = new Dictionary<string, string>();
// id is mandatory
metadataElementsDictionary.Add("id", _pkgName);
string version;
if (parsedMetadataHash.ContainsKey("moduleversion"))
{
version = parsedMetadataHash["moduleversion"].ToString();
}
else if (parsedMetadataHash.ContainsKey("version"))
{
version = parsedMetadataHash["version"].ToString();
}
else
{
// no version is specified for the nuspec
_cmdletPassedIn.WriteError(new ErrorRecord(
new ArgumentException("There is no package version specified. Please specify a version before publishing."),
"NoVersionFound",
ErrorCategory.InvalidArgument,
this));
return string.Empty;
}
// Look for Prerelease tag and then process any Tags in PrivateData > PSData
if (isModule)
{
if (parsedMetadataHash.ContainsKey("PrivateData"))
{
if (parsedMetadataHash["PrivateData"] is Hashtable privateData &&
privateData.ContainsKey("PSData"))
{
if (privateData["PSData"] is Hashtable psData)
{
if (psData.ContainsKey("prerelease") && psData["prerelease"] is string preReleaseVersion)
{
if (!string.IsNullOrEmpty(preReleaseVersion))
{
version = string.Format(@"{0}-{1}", version, preReleaseVersion);
}
}
if (psData.ContainsKey("licenseuri") && psData["licenseuri"] is string licenseUri)
{
metadataElementsDictionary.Add("licenseUrl", licenseUri.Trim());
}
if (psData.ContainsKey("projecturi") && psData["projecturi"] is string projectUri)
{
metadataElementsDictionary.Add("projectUrl", projectUri.Trim());
}
if (psData.ContainsKey("iconuri") && psData["iconuri"] is string iconUri)
{
metadataElementsDictionary.Add("iconUrl", iconUri.Trim());
}
if (psData.ContainsKey("releasenotes"))
{
if (psData["releasenotes"] is string releaseNotes)
{
metadataElementsDictionary.Add("releaseNotes", releaseNotes.Trim());
}
else if (psData["releasenotes"] is string[] releaseNotesArr)
{
metadataElementsDictionary.Add("releaseNotes", string.Join("\n", releaseNotesArr));
}
}
// defaults to false
// Value for requireAcceptLicense key needs to be a lowercase string representation of the boolean for it to be correctly parsed from psData file.
string requireLicenseAcceptance = psData.ContainsKey("requirelicenseacceptance") ? psData["requirelicenseacceptance"].ToString().ToLower() : "false";
metadataElementsDictionary.Add("requireLicenseAcceptance", requireLicenseAcceptance);
if (psData.ContainsKey("Tags") && psData["Tags"] is Array manifestTags)
{
var tagArr = new List<string>();
foreach (string tag in manifestTags)
{
tagArr.Add(tag);
}
parsedMetadataHash["tags"] = string.Join(" ", tagArr.ToArray());