-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathInstallHelper.cs
1665 lines (1464 loc) · 80 KB
/
InstallHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
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 NuGet.Protocol.Core.Types;
using NuGet.Versioning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
/// <summary>
/// Install helper class
/// </summary>
internal class InstallHelper
{
#region Members
public const string PSDataFileExt = ".psd1";
public const string PSScriptFileExt = ".ps1";
private const string MsgRepositoryNotTrusted = "Untrusted repository";
private const string MsgInstallUntrustedPackage = "You are installing the modules from an untrusted repository. If you trust this repository, change its Trusted value by running the Set-PSResourceRepository cmdlet. Are you sure you want to install the PSResource from '{0}'?";
private const string ScriptPATHWarning = "The installation path for the script does not currently appear in the {0} path environment variable. To make the script discoverable, add the script installation path, {1}, to the environment PATH variable.";
private CancellationToken _cancellationToken;
private readonly PSCmdlet _cmdletPassedIn;
private List<string> _pathsToInstallPkg;
private VersionRange _versionRange;
private NuGetVersion _nugetVersion;
private VersionType _versionType;
private string _versionString;
private bool _prerelease;
private bool _acceptLicense;
private bool _quiet;
private bool _reinstall;
private bool _force;
private bool _trustRepository;
private bool _asNupkg;
private bool _includeXml;
private bool _noClobber;
private bool _authenticodeCheck;
private bool _savePkg;
List<string> _pathsToSearch;
List<string> _pkgNamesToInstall;
private string _tmpPath;
private NetworkCredential _networkCredential;
private HashSet<string> _packagesOnMachine;
#endregion
#region Public Methods
public InstallHelper(PSCmdlet cmdletPassedIn, NetworkCredential networkCredential)
{
CancellationTokenSource source = new CancellationTokenSource();
_cancellationToken = source.Token;
_cmdletPassedIn = cmdletPassedIn;
_networkCredential = networkCredential;
}
/// <summary>
/// This method calls is the starting point for install processes and is called by Install, Update and Save cmdlets.
/// </summary>
public IEnumerable<PSResourceInfo> BeginInstallPackages(
string[] names,
VersionRange versionRange,
NuGetVersion nugetVersion,
VersionType versionType,
string versionString,
bool prerelease,
string[] repository,
bool acceptLicense,
bool quiet,
bool reinstall,
bool force,
bool trustRepository,
bool noClobber,
bool asNupkg,
bool includeXml,
bool skipDependencyCheck,
bool authenticodeCheck,
bool savePkg,
List<string> pathsToInstallPkg,
ScopeType? scope,
string tmpPath,
HashSet<string> pkgsInstalled)
{
_cmdletPassedIn.WriteDebug("In InstallHelper::BeginInstallPackages()");
_cmdletPassedIn.WriteDebug(string.Format("Parameters passed in >>> Name: '{0}'; VersionRange: '{1}'; NuGetVersion: '{2}'; VersionType: '{3}'; Version: '{4}'; Prerelease: '{5}'; Repository: '{6}'; " +
"AcceptLicense: '{7}'; Quiet: '{8}'; Reinstall: '{9}'; TrustRepository: '{10}'; NoClobber: '{11}'; AsNupkg: '{12}'; IncludeXml '{13}'; SavePackage '{14}'; TemporaryPath '{15}'; SkipDependencyCheck: '{16}'; " +
"AuthenticodeCheck: '{17}'; PathsToInstallPkg: '{18}'; Scope '{19}'",
string.Join(",", names),
versionRange != null ? (versionRange.OriginalString != null ? versionRange.OriginalString : string.Empty) : string.Empty,
nugetVersion != null ? nugetVersion.ToString() : string.Empty,
versionType.ToString(),
versionString != null ? versionString : String.Empty,
prerelease.ToString(),
repository != null ? string.Join(",", repository) : string.Empty,
acceptLicense.ToString(),
quiet.ToString(),
reinstall.ToString(),
trustRepository.ToString(),
noClobber.ToString(),
asNupkg.ToString(),
includeXml.ToString(),
savePkg.ToString(),
tmpPath ?? string.Empty,
skipDependencyCheck,
authenticodeCheck,
pathsToInstallPkg != null ? string.Join(",", pathsToInstallPkg) : string.Empty,
scope?.ToString() ?? string.Empty));
_versionRange = versionRange;
_nugetVersion = nugetVersion;
_versionType = versionType;
_versionString = versionString ?? String.Empty;
_prerelease = prerelease;
_acceptLicense = acceptLicense || force;
_authenticodeCheck = authenticodeCheck;
_quiet = quiet;
_reinstall = reinstall;
_force = force;
_trustRepository = trustRepository || force;
_noClobber = noClobber;
_asNupkg = asNupkg;
_includeXml = includeXml;
_savePkg = savePkg;
_pathsToInstallPkg = pathsToInstallPkg;
_tmpPath = tmpPath ?? Path.GetTempPath();
if (_versionRange == VersionRange.All)
{
_versionType = VersionType.NoVersion;
}
// Create list of installation paths to search.
_pathsToSearch = new List<string>();
_pkgNamesToInstall = names.ToList();
_packagesOnMachine = pkgsInstalled;
// _pathsToInstallPkg will only contain the paths specified within the -Scope param (if applicable)
// _pathsToSearch will contain all resource package subdirectories within _pathsToInstallPkg path locations
// e.g.:
// ./InstallPackagePath1/PackageA
// ./InstallPackagePath1/PackageB
// ./InstallPackagePath2/PackageC
// ./InstallPackagePath3/PackageD
foreach (var path in _pathsToInstallPkg)
{
_pathsToSearch.AddRange(Utils.GetSubDirectories(path));
}
// Go through the repositories and see which is the first repository to have the pkg version available
List<PSResourceInfo> installedPkgs = ProcessRepositories(
repository: repository,
trustRepository: _trustRepository,
skipDependencyCheck: skipDependencyCheck,
scope: scope ?? ScopeType.CurrentUser);
return installedPkgs;
}
#endregion
#region Private methods
/// <summary>
/// This method calls iterates through repositories (by priority order) to search for the packages to install.
/// It calls HTTP or NuGet API based install helper methods, according to repository type.
/// </summary>
private List<PSResourceInfo> ProcessRepositories(
string[] repository,
bool trustRepository,
bool skipDependencyCheck,
ScopeType scope)
{
_cmdletPassedIn.WriteDebug("In InstallHelper::ProcessRepositories()");
List<PSResourceInfo> allPkgsInstalled = new List<PSResourceInfo>();
if (repository != null && repository.Length != 0)
{
// Write error and disregard repository entries containing wildcards.
repository = Utils.ProcessNameWildcards(repository, removeWildcardEntries:false, out string[] errorMsgs, out _);
foreach (string error in errorMsgs)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new PSInvalidOperationException(error),
"ErrorFilteringNamesForUnsupportedWildcards",
ErrorCategory.InvalidArgument,
_cmdletPassedIn));
}
// If repository entries includes wildcards and non-wildcard names, write terminating error
// Ex: -Repository *Gallery, localRepo
bool containsWildcard = false;
bool containsNonWildcard = false;
foreach (string repoName in repository)
{
if (repoName.Contains("*"))
{
containsWildcard = true;
}
else
{
containsNonWildcard = true;
}
}
if (containsNonWildcard && containsWildcard)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException("Repository name with wildcard is not allowed when another repository without wildcard is specified."),
"RepositoryNamesWithWildcardsAndNonWildcardUnsupported",
ErrorCategory.InvalidArgument,
_cmdletPassedIn));
}
}
// Get repositories to search.
List<PSRepositoryInfo> repositoriesToSearch;
try
{
repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList);
if (repositoriesToSearch != null && repositoriesToSearch.Count == 0)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new PSArgumentException ("Cannot resolve -Repository name. Run 'Get-PSResourceRepository' to view all registered repositories."),
"RepositoryNameIsNotResolved",
ErrorCategory.InvalidArgument,
_cmdletPassedIn));
}
foreach (string error in errorList)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new PSInvalidOperationException(error),
"ErrorRetrievingSpecifiedRepository",
ErrorCategory.InvalidOperation,
_cmdletPassedIn));
}
}
catch (Exception e)
{
_cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorLoadingRepositoryStoreFile",
ErrorCategory.InvalidArgument,
_cmdletPassedIn));
return allPkgsInstalled;
}
var listOfRepositories = RepositorySettings.Read(repository, out string[] _);
var yesToAll = false;
var noToAll = false;
var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn, _networkCredential);
List<string> repositoryNamesToSearch = new List<string>();
bool sourceTrusted = false;
// Loop through all the repositories provided (in priority order) until there no more packages to install.
for (int i = 0; i < listOfRepositories.Count && _pkgNamesToInstall.Count > 0; i++)
{
PSRepositoryInfo currentRepository = listOfRepositories[i];
string repoName = currentRepository.Name;
sourceTrusted = currentRepository.Trusted || trustRepository;
_networkCredential = Utils.SetNetworkCredential(currentRepository, _networkCredential, _cmdletPassedIn);
ServerApiCall currentServer = ServerFactory.GetServer(currentRepository, _cmdletPassedIn, _networkCredential);
if (currentServer == null)
{
// this indicates that PSRepositoryInfo.APIVersion = PSRepositoryInfo.APIVersion.unknown
_cmdletPassedIn.WriteError(new ErrorRecord(
new PSInvalidOperationException($"Repository '{currentRepository.Name}' is not a known repository type that is supported. Please file an issue for support at https://github.com/PowerShell/PSResourceGet/issues"),
"RepositoryApiVersionUnknown",
ErrorCategory.InvalidArgument,
_cmdletPassedIn));
continue;
}
ResponseUtil currentResponseUtil = ResponseUtilFactory.GetResponseUtil(currentRepository);
bool installDepsForRepo = skipDependencyCheck;
// If no more packages to install, then return
if (_pkgNamesToInstall.Count == 0) {
return allPkgsInstalled;
}
_cmdletPassedIn.WriteVerbose($"Attempting to search for packages in '{repoName}'");
if (currentRepository.Trusted == false && !trustRepository && !_force)
{
_cmdletPassedIn.WriteVerbose("Checking if untrusted repository should be used");
if (!(yesToAll || noToAll))
{
// Prompt for installation of package from untrusted repository
var message = string.Format(CultureInfo.InvariantCulture, MsgInstallUntrustedPackage, repoName);
sourceTrusted = _cmdletPassedIn.ShouldContinue(message, MsgRepositoryNotTrusted, true, ref yesToAll, ref noToAll);
}
}
if (!sourceTrusted && !yesToAll)
{
continue;
}
repositoryNamesToSearch.Add(repoName);
if ((currentRepository.ApiVersion == PSRepositoryInfo.APIVersion.V3) && (!installDepsForRepo))
{
_cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies.");
installDepsForRepo = true;
}
var installedPkgs = InstallPackages(_pkgNamesToInstall.ToArray(), currentRepository, currentServer, currentResponseUtil, scope, skipDependencyCheck, findHelper);
foreach (var pkg in installedPkgs)
{
_pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
}
allPkgsInstalled.AddRange(installedPkgs);
}
if (_pkgNamesToInstall.Count > 0)
{
string repositoryWording = repositoryNamesToSearch.Count > 1 ? "registered repositories" : "repository";
_cmdletPassedIn.WriteError(new ErrorRecord(
new ResourceNotFoundException($"Package(s) '{string.Join(", ", _pkgNamesToInstall)}' could not be installed from {repositoryWording} '{String.Join(", ", repositoryNamesToSearch)}'."),
"InstallPackageFailure",
ErrorCategory.InvalidData,
_cmdletPassedIn));
}
return allPkgsInstalled;
}
/// <summary>
/// Checks if any of the package versions are already installed and if they are removes them from the list of packages to install.
/// </summary>
private List<PSResourceInfo> FilterByInstalledPkgs(List<PSResourceInfo> packages)
{
// Package install paths.
// _pathsToInstallPkg will only contain the paths specified within the -Scope param (if applicable).
// _pathsToSearch will contain all resource package subdirectories within _pathsToInstallPkg path locations.
// e.g.:
// ./InstallPackagePath1/PackageA
// ./InstallPackagePath1/PackageB
// ./InstallPackagePath2/PackageC
// ./InstallPackagePath3/PackageD
_cmdletPassedIn.WriteDebug("In InstallHelper::FilterByInstalledPkgs()");
// Get currently installed packages.
var getHelper = new GetHelper(_cmdletPassedIn);
var installedPackageNames = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);
foreach (var installedPkg in getHelper.GetInstalledPackages(
pkgs: packages,
pathsToSearch: _pathsToSearch))
{
installedPackageNames.Add(installedPkg.Name);
}
if (installedPackageNames.Count is 0)
{
return packages;
}
// Return only packages that are not already installed.
var filteredPackages = new List<PSResourceInfo>();
foreach (var pkg in packages)
{
if (!installedPackageNames.Contains(pkg.Name))
{
// Add packages that still need to be installed.
filteredPackages.Add(pkg);
}
else
{
// Remove from tracking list of packages to install.
pkg.AdditionalMetadata.TryGetValue("NormalizedVersion", out string normalizedVersion);
_cmdletPassedIn.WriteWarning($"Resource '{pkg.Name}' with version '{normalizedVersion}' is already installed. If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter");
// Remove from tracking list of packages to install.
_pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
}
}
return filteredPackages;
}
/// <summary>
/// Deletes temp directory and is called at end of install process.
/// </summary>
private bool TryDeleteDirectory(
string tempInstallPath,
out ErrorRecord errorMsg)
{
errorMsg = null;
try
{
Utils.DeleteDirectory(tempInstallPath);
}
catch (Exception e)
{
errorMsg = new ErrorRecord(
exception: e,
"errorDeletingTempInstallPath",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
return false;
}
return true;
}
/// <summary>
/// Moves file from the temp install path to desination path for install.
/// </summary>
private void MoveFilesIntoInstallPath(
PSResourceInfo pkgInfo,
bool isModule,
bool isLocalRepo,
string dirNameVersion,
string tempInstallPath,
string installPath,
string newVersion,
string moduleManifestVersion,
string scriptPath)
{
//_cmdletPassedIn.WriteDebug("In InstallHelper::MoveFilesIntoInstallPath()");
// Creating the proper installation path depending on whether pkg is a module or script
var newPathParent = isModule ? Path.Combine(installPath, pkgInfo.Name) : installPath;
var finalModuleVersionDir = isModule ? Path.Combine(installPath, pkgInfo.Name, moduleManifestVersion) : installPath;
// If script, just move the files over, if module, move the version directory over
var tempModuleVersionDir = (!isModule || isLocalRepo) ? dirNameVersion
: Path.Combine(tempInstallPath, pkgInfo.Name.ToLower(), newVersion);
// _cmdletPassedIn.WriteVerbose($"Installation source path is: '{tempModuleVersionDir}'");
// _cmdletPassedIn.WriteVerbose($"Installation destination path is: '{finalModuleVersionDir}'");
if (isModule)
{
// If new path does not exist
if (!Directory.Exists(newPathParent))
{
// _cmdletPassedIn.WriteVerbose($"Attempting to move '{tempModuleVersionDir}' to '{finalModuleVersionDir}'");
Directory.CreateDirectory(newPathParent);
Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
}
else
{
// _cmdletPassedIn.WriteVerbose($"Temporary module version directory is: '{tempModuleVersionDir}'");
if (Directory.Exists(finalModuleVersionDir))
{
// Delete the directory path before replacing it with the new module.
// If deletion fails (usually due to binary file in use), then attempt restore so that the currently
// installed module is not corrupted.
// _cmdletPassedIn.WriteVerbose($"Attempting to delete with restore on failure.'{finalModuleVersionDir}'");
Utils.DeleteDirectoryWithRestore(finalModuleVersionDir);
}
// _cmdletPassedIn.WriteVerbose($"Attempting to move '{tempModuleVersionDir}' to '{finalModuleVersionDir}'");
Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
}
}
else if (_asNupkg)
{
foreach (string file in Directory.GetFiles(tempInstallPath))
{
string fileName = Path.GetFileName(file);
string newFileName = string.Equals(Path.GetExtension(file), ".zip", StringComparison.OrdinalIgnoreCase) ?
$"{Path.GetFileNameWithoutExtension(file)}.nupkg" : fileName;
Utils.MoveFiles(Path.Combine(tempInstallPath, fileName), Path.Combine(installPath, newFileName));
}
}
else
{
string scriptInfoFolderPath = Path.Combine(installPath, "InstalledScriptInfos");
string scriptXML = pkgInfo.Name + "_InstalledScriptInfo.xml";
string scriptXmlFilePath = Path.Combine(scriptInfoFolderPath, scriptXML);
if (!_savePkg)
{
// Need to ensure "InstalledScriptInfos directory exists
if (!Directory.Exists(scriptInfoFolderPath))
{
// _cmdletPassedIn.WriteVerbose($"Created '{scriptInfoFolderPath}' path for scripts");
Directory.CreateDirectory(scriptInfoFolderPath);
}
// Need to delete old xml files because there can only be 1 per script
// _cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: '{1}'", scriptXmlFilePath, File.Exists(scriptXmlFilePath)));
if (File.Exists(scriptXmlFilePath))
{
// _cmdletPassedIn.WriteVerbose("Deleting script metadata XML");
File.Delete(Path.Combine(scriptInfoFolderPath, scriptXML));
}
// _cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML)));
Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML));
// Need to delete old script file, if that exists
// _cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt))));
if (File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt)))
{
// _cmdletPassedIn.WriteVerbose("Deleting script file");
File.Delete(Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt));
}
}
else {
if (_includeXml) {
_cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, scriptXML)));
Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, scriptXML));
}
}
// _cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt)));
Utils.MoveFiles(scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + PSScriptFileExt));
}
}
/// <summary>
/// Iterates through package names passed in and calls method to install each package and their dependencies.
/// </summary>
private List<PSResourceInfo> InstallPackages(
string[] pkgNamesToInstall,
PSRepositoryInfo repository,
ServerApiCall currentServer,
ResponseUtil currentResponseUtil,
ScopeType scope,
bool skipDependencyCheck,
FindHelper findHelper)
{
_cmdletPassedIn.WriteDebug("In InstallHelper::InstallPackages()");
List<PSResourceInfo> pkgsSuccessfullyInstalled = new List<PSResourceInfo>();
// Install parent package to the temp directory,
// Get the dependencies from the installed package,
// Install all dependencies to temp directory.
// If a single dependency fails to install, roll back by deleting the temp directory.
foreach (var parentPackage in pkgNamesToInstall)
{
string tempInstallPath = CreateInstallationTempPath();
try
{
// Hashtable has the key as the package name
// and value as a Hashtable of specific package info:
// packageName, { version = "", isScript = "", isModule = "", pkg = "", etc. }
// Install parent package to the temp directory.
Hashtable packagesHash = BeginPackageInstall(
searchVersionType: _versionType,
specificVersion: _nugetVersion,
versionRange: _versionRange,
pkgNameToInstall: parentPackage,
repository: repository,
currentServer: currentServer,
currentResponseUtil: currentResponseUtil,
tempInstallPath: tempInstallPath,
skipDependencyCheck: skipDependencyCheck,
packagesHash: new Hashtable(StringComparer.InvariantCultureIgnoreCase),
errRecord: out ErrorRecord errRecord);
// At this point all packages are installed to temp path.
if (errRecord != null)
{
if (errRecord.FullyQualifiedErrorId.Equals("PackageNotFound"))
{
_cmdletPassedIn.WriteVerbose(errRecord.Exception.Message);
}
else
{
_cmdletPassedIn.WriteError(errRecord);
}
continue;
}
if (packagesHash.Count == 0)
{
continue;
}
Hashtable parentPkgInfo = packagesHash[parentPackage] as Hashtable;
PSResourceInfo parentPkgObj = parentPkgInfo["psResourceInfoPkg"] as PSResourceInfo;
if (!skipDependencyCheck)
{
if (currentServer.Repository.ApiVersion == PSRepositoryInfo.APIVersion.V3)
{
_cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies.");
}
// Get the dependencies from the installed package.
if (parentPkgObj.Dependencies.Length > 0)
{
bool depFindFailed = false;
foreach (PSResourceInfo depPkg in findHelper.FindDependencyPackages(currentServer, currentResponseUtil, parentPkgObj, repository))
{
if (depPkg == null)
{
depFindFailed = true;
continue;
}
if (String.Equals(depPkg.Name, parentPkgObj.Name, StringComparison.OrdinalIgnoreCase))
{
continue;
}
NuGetVersion depVersion = null;
if (depPkg.AdditionalMetadata.ContainsKey("NormalizedVersion"))
{
if (!NuGetVersion.TryParse(depPkg.AdditionalMetadata["NormalizedVersion"] as string, out depVersion))
{
NuGetVersion.TryParse(depPkg.Version.ToString(), out depVersion);
}
}
packagesHash = BeginPackageInstall(
searchVersionType: VersionType.SpecificVersion,
specificVersion: depVersion,
versionRange: null,
pkgNameToInstall: depPkg.Name,
repository: repository,
currentServer: currentServer,
currentResponseUtil: currentResponseUtil,
tempInstallPath: tempInstallPath,
skipDependencyCheck: skipDependencyCheck,
packagesHash: packagesHash,
errRecord: out ErrorRecord installPkgErrRecord);
if (installPkgErrRecord != null)
{
_cmdletPassedIn.WriteError(installPkgErrRecord);
continue;
}
}
if (depFindFailed)
{
continue;
}
}
}
// If -WhatIf is passed in, early out.
if (!_cmdletPassedIn.ShouldProcess("Exit ShouldProcess"))
{
return pkgsSuccessfullyInstalled;
}
// Parent package and dependencies are now installed to temp directory.
// Try to move all package directories from temp directory to final destination.
if (!TryMoveInstallContent(tempInstallPath, scope, packagesHash))
{
_cmdletPassedIn.WriteError(new ErrorRecord(
new InvalidOperationException(),
"InstallPackageTryMoveContentFailure",
ErrorCategory.InvalidOperation,
_cmdletPassedIn));
}
else
{
foreach (string pkgName in packagesHash.Keys)
{
Hashtable pkgInfo = packagesHash[pkgName] as Hashtable;
pkgsSuccessfullyInstalled.Add(pkgInfo["psResourceInfoPkg"] as PSResourceInfo);
// Add each pkg to _packagesOnMachine (ie pkgs fully installed on the machine).
_packagesOnMachine.Add($"{pkgName}{pkgInfo["pkgVersion"]}");
}
}
}
catch (Exception e)
{
_cmdletPassedIn.WriteError(new ErrorRecord(
e,
"InstallPackageFailure",
ErrorCategory.InvalidOperation,
_cmdletPassedIn));
throw e;
}
finally
{
DeleteInstallationTempPath(tempInstallPath);
}
}
return pkgsSuccessfullyInstalled;
}
/// <summary>
/// Installs a single package to the temporary path.
/// </summary>
private Hashtable BeginPackageInstall(
VersionType searchVersionType,
NuGetVersion specificVersion,
VersionRange versionRange,
string pkgNameToInstall,
PSRepositoryInfo repository,
ServerApiCall currentServer,
ResponseUtil currentResponseUtil,
string tempInstallPath,
bool skipDependencyCheck,
Hashtable packagesHash,
out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In InstallHelper::InstallPackage()");
FindResults responses = null;
errRecord = null;
// Find the parent package that needs to be installed
switch (searchVersionType)
{
case VersionType.VersionRange:
responses = currentServer.FindVersionGlobbing(pkgNameToInstall, versionRange, _prerelease, ResourceType.None, getOnlyLatest: true, out ErrorRecord findVersionGlobbingErrRecord);
// Server level globbing API will not populate errRecord for empty response, so must check for empty response and early out
if (findVersionGlobbingErrRecord != null || responses.IsFindResultsEmpty())
{
errRecord = findVersionGlobbingErrRecord;
return packagesHash;
}
break;
case VersionType.SpecificVersion:
string nugetVersionString = specificVersion.ToNormalizedString(); // 3.0.17-beta
responses = currentServer.FindVersion(pkgNameToInstall, nugetVersionString, ResourceType.None, out ErrorRecord findVersionErrRecord);
if (findVersionErrRecord != null)
{
errRecord = findVersionErrRecord;
return packagesHash;
}
break;
default:
// VersionType.NoVersion
responses = currentServer.FindName(pkgNameToInstall, _prerelease, ResourceType.None, out ErrorRecord findNameErrRecord);
if (findNameErrRecord != null)
{
errRecord = findNameErrRecord;
return packagesHash;
}
break;
}
// Convert parent package to PSResourceInfo
PSResourceInfo pkgToInstall = null;
foreach (PSResourceResult currentResult in currentResponseUtil.ConvertToPSResourceResult(responses))
{
if (currentResult.exception != null && !currentResult.exception.Message.Equals(string.Empty))
{
errRecord = new ErrorRecord(
currentResult.exception,
"FindConvertToPSResourceFailure",
ErrorCategory.ObjectNotFound,
_cmdletPassedIn);
}
else if (searchVersionType == VersionType.VersionRange)
{
// Check to see if version falls within version range
PSResourceInfo foundPkg = currentResult.returnedObject;
string versionStr = $"{foundPkg.Version}";
if (foundPkg.IsPrerelease)
{
versionStr += $"-{foundPkg.Prerelease}";
}
if (NuGetVersion.TryParse(versionStr, out NuGetVersion version)
&& _versionRange.Satisfies(version))
{
pkgToInstall = foundPkg;
break;
}
} else {
pkgToInstall = currentResult.returnedObject;
break;
}
}
if (pkgToInstall == null)
{
return packagesHash;
}
pkgToInstall.RepositorySourceLocation = repository.Uri.ToString();
pkgToInstall.AdditionalMetadata.TryGetValue("NormalizedVersion", out string pkgVersion);
if (pkgVersion == null) {
pkgVersion = pkgToInstall.Version.ToString();
}
// Check to see if the pkg is already installed (ie the pkg is installed and the version satisfies the version range provided via param)
if (!_reinstall)
{
string currPkgNameVersion = $"{pkgToInstall.Name}{pkgToInstall.Version}";
if (_packagesOnMachine.Contains(currPkgNameVersion))
{
_cmdletPassedIn.WriteWarning($"Resource '{pkgToInstall.Name}' with version '{pkgVersion}' is already installed. If you would like to reinstall, please run the cmdlet again with the -Reinstall parameter");
// Remove from tracking list of packages to install.
_pkgNamesToInstall.RemoveAll(x => x.Equals(pkgToInstall.Name, StringComparison.InvariantCultureIgnoreCase));
return packagesHash;
}
}
if (packagesHash.ContainsKey(pkgToInstall.Name))
{
return packagesHash;
}
Hashtable updatedPackagesHash = packagesHash;
// -WhatIf processing.
if (_savePkg && !_cmdletPassedIn.ShouldProcess($"Package to save: '{pkgToInstall.Name}', version: '{pkgVersion}'"))
{
if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name))
{
updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase)
{
{ "isModule", "" },
{ "isScript", "" },
{ "psResourceInfoPkg", pkgToInstall },
{ "tempDirNameVersionPath", tempInstallPath },
{ "pkgVersion", "" },
{ "scriptPath", "" },
{ "installPath", "" }
});
}
}
else if (!_cmdletPassedIn.ShouldProcess($"Package to install: '{pkgToInstall.Name}', version: '{pkgVersion}'"))
{
if (!updatedPackagesHash.ContainsKey(pkgToInstall.Name))
{
updatedPackagesHash.Add(pkgToInstall.Name, new Hashtable(StringComparer.InvariantCultureIgnoreCase)
{
{ "isModule", "" },
{ "isScript", "" },
{ "psResourceInfoPkg", pkgToInstall },
{ "tempDirNameVersionPath", tempInstallPath },
{ "pkgVersion", "" },
{ "scriptPath", "" },
{ "installPath", "" }
});
}
}
else
{
// Concurrently Updates
// Find all dependencies
string pkgName = pkgToInstall.Name;
if (!skipDependencyCheck)
{
List<PSResourceInfo> allDependencies = FindAllDependencies(currentServer, currentResponseUtil, pkgToInstall, repository);
return InstallParentAndDependencyPackages(pkgToInstall, allDependencies, currentServer, tempInstallPath, packagesHash, updatedPackagesHash, pkgToInstall);
}
else {
// TODO: check this version and prerelease combo
Stream responseStream = currentServer.InstallPackage(pkgToInstall.Name, pkgToInstall.Version.ToString(), true, out ErrorRecord installNameErrRecord);
if (installNameErrRecord != null)
{
errRecord = installNameErrRecord;
return packagesHash;
}
bool installedToTempPathSuccessfully = _asNupkg ? TrySaveNupkgToTempPath(responseStream, tempInstallPath, pkgToInstall.Name, pkgToInstall.Version.ToString(), pkgToInstall, packagesHash, out updatedPackagesHash, out errRecord) :
TryInstallToTempPath(responseStream, tempInstallPath, pkgToInstall.Name, pkgToInstall.Version.ToString(), pkgToInstall, packagesHash, out updatedPackagesHash, out errRecord);
if (!installedToTempPathSuccessfully)
{
return packagesHash;
}
}
}
return updatedPackagesHash;
}
// Concurrency Updates
private List<PSResourceInfo> FindAllDependencies(ServerApiCall currentServer, ResponseUtil currentResponseUtil, PSResourceInfo pkgToInstall, PSRepositoryInfo repository)
{
if (currentServer.Repository.ApiVersion == PSRepositoryInfo.APIVersion.V3)
{
_cmdletPassedIn.WriteWarning("Installing dependencies is not currently supported for V3 server protocol repositories. The package will be installed without installing dependencies.");
}
var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn, _networkCredential);
_cmdletPassedIn.WriteDebug($"Finding dependency packages for '{pkgToInstall.Name}'");
// the last package added will be the parent package.
List<PSResourceInfo> allDependencies = findHelper.FindDependencyPackages(currentServer, currentResponseUtil, pkgToInstall, repository).ToList();
// allDependencies contains parent package as well
foreach (PSResourceInfo pkg in allDependencies)
{
// Console.WriteLine($"{pkg.Name}: {pkg.Version}");
}
return allDependencies;
}
// Concurrently Updates
private Hashtable InstallParentAndDependencyPackages(PSResourceInfo parentPkg, List<PSResourceInfo> allDependencies, ServerApiCall currentServer, string tempInstallPath, Hashtable packagesHash, Hashtable updatedPackagesHash, PSResourceInfo pkgToInstall)
{
List<ErrorRecord> errors = new List<ErrorRecord>();
// If installing more than 5 packages, do so concurrently
if (allDependencies.Count > 5)
{
// Set the maximum degree of parallelism to 32 (Invoke-Command has default of 32, that's where we got this number from)
Parallel.ForEach(allDependencies, new ParallelOptions { MaxDegreeOfParallelism = 32 }, depPkg =>
{
var depPkgName = depPkg.Name;
var depPkgVersion = depPkg.Version.ToString();
// Console.WriteLine($"Processing number: {depPkg}, Thread ID: {Task.CurrentId}");
Stream responseStream = currentServer.InstallPackage(depPkgName, depPkgVersion, true, out ErrorRecord installNameErrRecord);
if (installNameErrRecord != null)
{
errors.Add(installNameErrRecord);
}
ErrorRecord tempSaveErrRecord = null, tempInstallErrRecord = null;
bool installedToTempPathSuccessfully = _asNupkg ? TrySaveNupkgToTempPath(responseStream, tempInstallPath, depPkgName, depPkgVersion, depPkg, packagesHash, out updatedPackagesHash, out tempSaveErrRecord) :
TryInstallToTempPath(responseStream, tempInstallPath, depPkgName, depPkgVersion, depPkg, packagesHash, out updatedPackagesHash, out tempInstallErrRecord);
if (!installedToTempPathSuccessfully)
{
errors.Add(tempSaveErrRecord ?? tempInstallErrRecord);
}
});
if (errors.Count > 0)
{
// Write out all errors collected from Parallel.ForEach
foreach (var err in errors)
{
_cmdletPassedIn.WriteError(err);
}
return packagesHash;
}
// Install parent package
Stream responseStream = currentServer.InstallPackage(parentPkg.Name, parentPkg.Version.ToString(), true, out ErrorRecord installNameErrRecord);
if (installNameErrRecord != null)
{
_cmdletPassedIn.WriteError(installNameErrRecord);
return packagesHash;
}
ErrorRecord tempSaveErrRecord = null, tempInstallErrRecord = null;
bool installedToTempPathSuccessfully = _asNupkg ? TrySaveNupkgToTempPath(responseStream, tempInstallPath, parentPkg.Name, parentPkg.Version.ToString(), pkgToInstall, packagesHash, out updatedPackagesHash, out tempSaveErrRecord) :
TryInstallToTempPath(responseStream, tempInstallPath, parentPkg.Name, parentPkg.Version.ToString(), pkgToInstall, packagesHash, out updatedPackagesHash, out tempInstallErrRecord);
if (!installedToTempPathSuccessfully)
{
_cmdletPassedIn.WriteError(tempSaveErrRecord ?? tempInstallErrRecord);
return packagesHash;
}
return updatedPackagesHash;
}
else
{
// Install the good old fashioned way
// Make sure to install dependencies first, then install parent pkg
allDependencies.Add(parentPkg);
foreach (var pkgToBeInstalled in allDependencies)
{
var pkgToInstallName = pkgToBeInstalled.Name;
var pkgToInstallVersion = pkgToBeInstalled.Version.ToString();
Stream responseStream = currentServer.InstallPackage(pkgToInstallName, pkgToInstallVersion, true, out ErrorRecord installNameErrRecord);