Skip to content
75 changes: 40 additions & 35 deletions src/code/InstallHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ internal class InstallHelper : PSCmdlet
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 CancellationToken _cancellationToken;
private readonly bool _savePkg;
private readonly PSCmdlet _cmdletPassedIn;
private List<string> _pathsToInstallPkg;
private VersionRange _versionRange;
Expand All @@ -46,21 +45,20 @@ internal class InstallHelper : PSCmdlet
private bool _force;
private bool _trustRepository;
private PSCredential _credential;
private string _specifiedPath;
private bool _asNupkg;
private bool _includeXML;
private bool _noClobber;
private bool _savePkg;
List<string> _pathsToSearch;

#endregion

#region Public methods

public InstallHelper(bool savePkg, PSCmdlet cmdletPassedIn)
public InstallHelper(PSCmdlet cmdletPassedIn)
{
CancellationTokenSource source = new CancellationTokenSource();
_cancellationToken = source.Token;
_savePkg = savePkg;
_cmdletPassedIn = cmdletPassedIn;
}

Expand All @@ -76,23 +74,26 @@ public List<PSResourceInfo> InstallPackages(
bool trustRepository,
bool noClobber,
PSCredential credential,
string specifiedPath,
bool asNupkg,
bool includeXML,
bool skipDependencyCheck,
bool savePkg,
List<string> pathsToInstallPkg)
{
_cmdletPassedIn.WriteVerbose(string.Format("Parameters passed in >>> Name: '{0}'; Version: '{1}'; Prerelease: '{2}'; Repository: '{3}'; " +
"AcceptLicense: '{4}'; Quiet: '{5}'; Reinstall: '{6}'; TrustRepository: '{7}'; NoClobber: '{8}'",
"AcceptLicense: '{4}'; Quiet: '{5}'; Reinstall: '{6}'; TrustRepository: '{7}'; NoClobber: '{8}'; AsNupkg: '{9}'; IncludeXML '{10}'; SavePackage '{11}'",
string.Join(",", names),
versionRange != null ? versionRange.OriginalString : string.Empty,
versionRange != null ? (versionRange.OriginalString != null ? versionRange.OriginalString : string.Empty) : string.Empty,
prerelease.ToString(),
repository != null ? string.Join(",", repository) : string.Empty,
acceptLicense.ToString(),
quiet.ToString(),
reinstall.ToString(),
trustRepository.ToString(),
noClobber.ToString()));
noClobber.ToString(),
asNupkg.ToString(),
includeXML.ToString(),
savePkg.ToString()));

_versionRange = versionRange;
_prerelease = prerelease;
Expand All @@ -103,9 +104,9 @@ public List<PSResourceInfo> InstallPackages(
_trustRepository = trustRepository || force;
_noClobber = noClobber;
_credential = credential;
_specifiedPath = specifiedPath;
_asNupkg = asNupkg;
_includeXML = includeXML;
_savePkg = savePkg;
_pathsToInstallPkg = pathsToInstallPkg;

// Create list of installation paths to search.
Expand Down Expand Up @@ -379,15 +380,7 @@ private List<PSResourceInfo> InstallPackage(
globalPackagesFolder: tempInstallPath,
logger: NullLogger.Instance,
token: _cancellationToken).GetAwaiter().GetResult();

if (_asNupkg) // this is Save functionality
{
DirectoryInfo nupkgPath = new DirectoryInfo(((System.IO.FileStream)result.PackageStream).Name);
File.Copy(nupkgPath.FullName, Path.Combine(tempInstallPath, pkgIdentity.Id + pkgIdentity.Version + ".nupkg"));

continue;
}


// Create the package extraction context
PackageExtractionContext packageExtractionContext = new PackageExtractionContext(
packageSaveMode: PackageSaveMode.Nupkg,
Expand Down Expand Up @@ -444,10 +437,8 @@ private List<PSResourceInfo> InstallPackage(

_cmdletPassedIn.WriteVerbose(string.Format("Successfully able to download package from source to: '{0}'", tempInstallPath));

// Prompt if module requires license acceptance (need to read info license acceptance info from the module manifest)
// pkgIdentity.Version.Version gets the version without metadata or release labels.
string newVersion = pkgIdentity.Version.ToNormalizedString();

string normalizedVersionNoPrereleaseLabel = newVersion;
if (pkgIdentity.Version.IsPrerelease)
{
Expand All @@ -463,6 +454,35 @@ private List<PSResourceInfo> InstallPackage(
// Check if the package is a module or a script
var isModule = File.Exists(modulePath);

string installPath;
if (_savePkg)
{
// For save the installation path is what is passed in via -Path
installPath = _pathsToInstallPkg.FirstOrDefault();

// If saving as nupkg simply copy the nupkg and move onto next iteration of loop
// asNupkg functionality only applies to Save-PSResource
if (_asNupkg)
{
var nupkgFile = pkgIdentity.ToString().ToLower() + ".nupkg";
File.Copy(Path.Combine(tempDirNameVersion, nupkgFile), Path.Combine(installPath, nupkgFile));

_cmdletPassedIn.WriteVerbose(string.Format("'{0}' moved into file path '{1}'", nupkgFile, installPath));
pkgsSuccessfullyInstalled.Add(pkg);

continue;
}
}
else
{
// PSModules:
/// ./Modules
/// ./Scripts
/// _pathsToInstallPkg is sorted by desirability, Find will pick the pick the first Script or Modules path found in the list
installPath = isModule ? _pathsToInstallPkg.Find(path => path.EndsWith("Modules", StringComparison.InvariantCultureIgnoreCase))
: _pathsToInstallPkg.Find(path => path.EndsWith("Scripts", StringComparison.InvariantCultureIgnoreCase));
}

if (isModule)
{
var moduleManifest = Path.Combine(tempDirNameVersion, pkgIdentity.Id + ".psd1");
Expand Down Expand Up @@ -500,21 +520,6 @@ private List<PSResourceInfo> InstallPackage(
// Delete the extra nupkg related files that are not needed and not part of the module/script
DeleteExtraneousFiles(pkgIdentity, tempDirNameVersion);

string installPath;
if (_savePkg)
{
// For save the installation path is what is passed in via -Path
installPath = _pathsToInstallPkg.FirstOrDefault();
}
else {
// PSModules:
/// ./Modules
/// ./Scripts
/// _pathsToInstallPkg is sorted by desirability, Find will pick the pick the first Script or Modules path found in the list
installPath = isModule ? _pathsToInstallPkg.Find(path => path.EndsWith("Modules", StringComparison.InvariantCultureIgnoreCase))
: _pathsToInstallPkg.Find(path => path.EndsWith("Scripts", StringComparison.InvariantCultureIgnoreCase));
}

if (_includeXML)
{
CreateMetadataXMLFile(tempDirNameVersion, installPath, pkg, isModule);
Expand Down
20 changes: 10 additions & 10 deletions src/code/InstallPSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ protected override void BeginProcessing()

_pathsToInstallPkg = Utils.GetAllInstallationPaths(this, Scope);

_installHelper = new InstallHelper(savePkg: false, cmdletPassedIn: this);
_installHelper = new InstallHelper(cmdletPassedIn: this);
}

protected override void ProcessRecord()
Expand Down Expand Up @@ -260,18 +260,18 @@ private void ProcessInstallHelper(string[] pkgNames, bool pkgPrerelease, string[
trustRepository: TrustRepository,
noClobber: NoClobber,
credential: Credential,
specifiedPath: null,
asNupkg: false,
includeXML: true,
skipDependencyCheck: SkipDependencyCheck,
pathsToInstallPkg: _pathsToInstallPkg);

if (PassThru)
{
foreach (PSResourceInfo pkg in installedPkgs)
{
WriteObject(pkg);
}
savePkg: false,
pathsToInstallPkg: _pathsToInstallPkg);

if (PassThru)
{
foreach (PSResourceInfo pkg in installedPkgs)
{
WriteObject(pkg);
}
}
}

Expand Down
12 changes: 5 additions & 7 deletions src/code/SavePSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,8 @@ public sealed class SavePSResource : PSCmdlet
[Parameter(ParameterSetName = InputObjectParameterSet)]
public PSCredential Credential { get; set; }

/*
/// <summary>
/// Saves as a .nupkg
/// Saves the resource as a .nupkg
/// </summary>
[Parameter()]
public SwitchParameter AsNupkg { get; set; }
Expand All @@ -79,7 +78,6 @@ public sealed class SavePSResource : PSCmdlet
/// </summary>
[Parameter()]
public SwitchParameter IncludeXML { get; set; }
*/

/// <summary>
/// The destination where the resource is to be installed. Works for all resource types.
Expand Down Expand Up @@ -152,7 +150,7 @@ protected override void BeginProcessing()
_path = SessionState.Path.CurrentLocation.Path;
}

_installHelper = new InstallHelper(savePkg: true, cmdletPassedIn: this);
_installHelper = new InstallHelper(cmdletPassedIn: this);
}

protected override void ProcessRecord()
Expand Down Expand Up @@ -254,10 +252,10 @@ private void ProcessSaveHelper(string[] pkgNames, bool pkgPrerelease, string[] p
trustRepository: TrustRepository,
credential: Credential,
noClobber: false,
specifiedPath: _path,
asNupkg: false,
includeXML: false,
asNupkg: AsNupkg,
includeXML: IncludeXML,
skipDependencyCheck: SkipDependencyCheck,
savePkg: true,
pathsToInstallPkg: new List<string> { _path } );

if (PassThru)
Expand Down
6 changes: 2 additions & 4 deletions src/code/UpdatePSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,7 @@ protected override void BeginProcessing()
cancellationToken: _cancellationTokenSource.Token,
cmdletPassedIn: this);

_installHelper = new InstallHelper(
savePkg: false,
cmdletPassedIn: this);
_installHelper = new InstallHelper(cmdletPassedIn: this);
}

protected override void ProcessRecord()
Expand Down Expand Up @@ -176,10 +174,10 @@ protected override void ProcessRecord()
trustRepository: TrustRepository,
credential: Credential,
noClobber: false,
specifiedPath: null,
asNupkg: false,
includeXML: true,
skipDependencyCheck: SkipDependencyCheck,
savePkg: false,
pathsToInstallPkg: _pathsToInstallPkg);

if (PassThru)
Expand Down
24 changes: 24 additions & 0 deletions test/SavePSResource.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,30 @@ Describe 'Test Save-PSResource for PSResources' {
(Get-ChildItem -Path $pkgDir.FullName).Count | Should -Be 1
}

It "Save module as a nupkg" {
Save-PSResource -Name "TestModule" -Version "1.3.0" -Repository $TestGalleryName -Path $SaveDir -AsNupkg
write-host $SaveDir
write-host
$pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq "testmodule.1.3.0.nupkg"
$pkgDir | Should -Not -BeNullOrEmpty
}

It "Save script as a nupkg" {
Save-PSResource -Name "TestTestScript" -Version "1.3.1" -Repository $TestGalleryName -Path $SaveDir -AsNupkg
$pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq "testtestscript.1.3.1.nupkg"
$pkgDir | Should -Not -BeNullOrEmpty
}

It "Save module and include XML metadata file" {
Save-PSResource -Name "TestModule" -Version "1.3.0" -Repository $TestGalleryName -Path $SaveDir -IncludeXML
$pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq "TestModule"
$pkgDir | Should -Not -BeNullOrEmpty
$pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName
$pkgDirVersion.Name | Should -Be "1.3.0"
$xmlFile = Get-ChildItem -Path $pkgDirVersion.FullName | Where-Object Name -eq "PSGetModuleInfo.xml"
$xmlFile | Should -Not -BeNullOrEmpty
}

It "Save module using -PassThru" {
$res = Save-PSResource -Name "TestModule" -Version "1.3.0" -Repository $TestGalleryName -Path $SaveDir -PassThru
$res.Name | Should -Be "TestModule"
Expand Down