Skip to content

Commit

Permalink
Add module prefix for Publish-PSResource cmdlet (#1694)
Browse files Browse the repository at this point in the history
  • Loading branch information
adityapatwardhan authored Aug 26, 2024
1 parent e9e8ecb commit c9cec29
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 41 deletions.
21 changes: 14 additions & 7 deletions src/code/ContainerRegistryServerAPICalls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1129,15 +1129,18 @@ private static Collection<KeyValuePair<string, string>> GetDefaultHeaders(string
internal bool PushNupkgContainerRegistry(string psd1OrPs1File,
string outputNupkgDir,
string packageName,
string modulePrefix,
NuGetVersion packageVersion,
ResourceType resourceType,
Hashtable parsedMetadataHash,
Hashtable dependencies,
Hashtable parsedMetadataHash,
Hashtable dependencies,
out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::PushNupkgContainerRegistry()");
string fullNupkgFile = System.IO.Path.Combine(outputNupkgDir, packageName + "." + packageVersion.ToNormalizedString() + ".nupkg");
string packageNameLowercase = packageName.ToLower();

string pkgNameForUpload = string.IsNullOrEmpty(modulePrefix) ? packageName : modulePrefix + "/" + packageName;
string packageNameLowercase = pkgNameForUpload.ToLower();

// Get access token (includes refresh tokens)
_cmdletPassedIn.WriteVerbose($"Get access token for container registry server.");
Expand Down Expand Up @@ -1179,8 +1182,8 @@ internal bool PushNupkgContainerRegistry(string psd1OrPs1File,
return false;
}

// Create and upload manifest
TryCreateAndUploadManifest(fullNupkgFile, nupkgDigest, configDigest, packageName, resourceType, metadataJson, configFilePath, packageVersion, containerRegistryAccessToken, out errRecord);
// Create and upload manifest
TryCreateAndUploadManifest(fullNupkgFile, nupkgDigest, configDigest, packageName, modulePrefix, resourceType, metadataJson, configFilePath, packageVersion, containerRegistryAccessToken, out errRecord);
if (errRecord != null)
{
return false;
Expand All @@ -1195,7 +1198,7 @@ internal bool PushNupkgContainerRegistry(string psd1OrPs1File,
/// </summary>
private string UploadNupkgFile(string packageNameLowercase, string containerRegistryAccessToken, string fullNupkgFile, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadNupkgFile()");
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadNupkgFile()");
_cmdletPassedIn.WriteVerbose("Start uploading blob");
string nupkgDigest = string.Empty;
errRecord = null;
Expand Down Expand Up @@ -1349,6 +1352,7 @@ private bool TryCreateAndUploadManifest(string fullNupkgFile,
string nupkgDigest,
string configDigest,
string packageName,
string modulePrefix,
ResourceType resourceType,
string metadataJson,
string configFilePath,
Expand All @@ -1358,7 +1362,10 @@ private bool TryCreateAndUploadManifest(string fullNupkgFile,
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::TryCreateAndUploadManifest()");
errRecord = null;
string packageNameLowercase = packageName.ToLower();

string pkgNameForUpload = string.IsNullOrEmpty(modulePrefix) ? packageName : modulePrefix + "/" + packageName;
string packageNameLowercase = pkgNameForUpload.ToLower();

FileInfo nupkgFile = new FileInfo(fullNupkgFile);
var fileSize = nupkgFile.Length;
var fileName = System.IO.Path.GetFileName(fullNupkgFile);
Expand Down
31 changes: 16 additions & 15 deletions src/code/PublishHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ internal PublishHelper(PSCmdlet cmdlet, string path, string destinationPath, boo
outputNupkgDir = destinationPath;
}

internal PublishHelper(PSCmdlet cmdlet,
PSCredential credential,
string apiKey,
string path,
string destinationPath,
bool skipModuleManifestValidate,
internal PublishHelper(PSCmdlet cmdlet,
PSCredential credential,
string apiKey,
string path,
string destinationPath,
bool skipModuleManifestValidate,
CancellationToken cancellationToken,
bool isNupkgPathSpecified)
{
Expand All @@ -105,7 +105,7 @@ internal PublishHelper(PSCmdlet cmdlet,

#region Internal Methods

internal void PackResource()
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)))
Expand Down Expand Up @@ -136,7 +136,7 @@ out string[] _
}

parsedMetadata = scriptToPublish.ToHashtable();

_pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToScriptFileToPublish);
}
else
Expand Down Expand Up @@ -320,7 +320,7 @@ out string[] _
}
}

internal void PushResource(string Repository, bool SkipDependenciesCheck, NetworkCredential _networkCrendential)
internal void PushResource(string Repository, string modulePrefix, bool SkipDependenciesCheck, NetworkCredential _networkCrendential)
{
try
{
Expand Down Expand Up @@ -410,7 +410,8 @@ internal void PushResource(string Repository, bool SkipDependenciesCheck, Networ
ContainerRegistryServerAPICalls containerRegistryServer = new ContainerRegistryServerAPICalls(repository, _cmdletPassedIn, _networkCredential, userAgentString);

var pkgMetadataFile = (resourceType == ResourceType.Script) ? pathToScriptFileToPublish : pathToModuleManifestToPublish;
if (!containerRegistryServer.PushNupkgContainerRegistry(pkgMetadataFile, outputNupkgDir, _pkgName, _pkgVersion, resourceType, parsedMetadata, dependencies, out ErrorRecord pushNupkgContainerRegistryError))

if (!containerRegistryServer.PushNupkgContainerRegistry(pkgMetadataFile, outputNupkgDir, _pkgName, modulePrefix, _pkgVersion, resourceType, parsedMetadata, dependencies, out ErrorRecord pushNupkgContainerRegistryError))
{
_cmdletPassedIn.WriteError(pushNupkgContainerRegistryError);
// exit out of processing
Expand Down Expand Up @@ -593,7 +594,7 @@ private bool PackNupkg(string outputDir, string outputNupkgDir, string nuspecFil
private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, out ErrorRecord error)
{
_cmdletPassedIn.WriteDebug("In PublishPSResource::PushNupkg()");

string fullNupkgFile;
if (_isNupkgPathSpecified)
{
Expand Down Expand Up @@ -1097,12 +1098,12 @@ private string CreateNuspec(
private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
{
_cmdletPassedIn.WriteDebug("In PublishHelper::ParseRequiredModules()");

if (!parsedMetadataHash.ContainsKey("requiredmodules"))
{
return null;
}

LanguagePrimitives.TryConvertTo<object[]>(parsedMetadataHash["requiredmodules"], out object[] requiredModules);

// Required modules can be:
Expand Down Expand Up @@ -1136,7 +1137,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
dependenciesHash.Add(moduleName, string.Empty);
}
}

var externalModuleDeps = parsedMetadataHash.ContainsKey("ExternalModuleDependencies") ?
parsedMetadataHash["ExternalModuleDependencies"] : null;

Expand All @@ -1157,7 +1158,7 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash)
private bool CheckDependenciesExist(Hashtable dependencies, string repositoryName)
{
_cmdletPassedIn.WriteDebug("In PublishHelper::CheckDependenciesExist()");

// Check to see that all dependencies are in the repository
// Searches for each dependency in the repository the pkg is being pushed to,
// If the dependency is not there, error
Expand Down
37 changes: 31 additions & 6 deletions src/code/PublishPSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using System;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Threading;
Expand All @@ -16,12 +17,13 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
"PSResource",
SupportsShouldProcess = true)]
[Alias("pbres")]
public sealed class PublishPSResource : PSCmdlet
public sealed class PublishPSResource : PSCmdlet, IDynamicParameters
{
#region Parameters

private const string PathParameterSet = "PathParameterSet";
private const string NupkgPathParameterSet = "NupkgPathParameterSet";
private ContainerRegistryDynamicParameters _pkgPrefix;

/// <summary>
/// Specifies the API key that you want to use to publish a module to the online gallery.
Expand Down Expand Up @@ -117,6 +119,21 @@ public PSCredential ProxyCredential {

#endregion

#region DynamicParameters
public object GetDynamicParameters()
{
PSRepositoryInfo repository = RepositorySettings.Read(new[] { Repository }, out string[] _).FirstOrDefault();
if (repository is not null && repository.ApiVersion == PSRepositoryInfo.APIVersion.ContainerRegistry)
{
_pkgPrefix = new ContainerRegistryDynamicParameters();
return _pkgPrefix;
}

return null;
}

#endregion

#region Members

private CancellationToken _cancellationToken;
Expand Down Expand Up @@ -145,10 +162,10 @@ protected override void BeginProcessing()
RepositorySettings.CheckRepositoryStore();

_publishHelper = new PublishHelper(
this,
Credential,
ApiKey,
Path,
this,
Credential,
ApiKey,
Path,
DestinationPath,
SkipModuleManifestValidate,
_cancellationToken,
Expand All @@ -169,10 +186,18 @@ protected override void EndProcessing()
return;
}

_publishHelper.PushResource(Repository, SkipDependenciesCheck, _networkCredential);
string modulePrefix = _pkgPrefix?.ModulePrefix;

_publishHelper.PushResource(Repository, modulePrefix, SkipDependenciesCheck, _networkCredential);
}

#endregion

}

public class ContainerRegistryDynamicParameters
{
[Parameter]
public string ModulePrefix { get; set; }
}
}
7 changes: 3 additions & 4 deletions src/code/ServerApiCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using System.Text;
using System.Runtime.ExceptionServices;
using System.Management.Automation;
using System;

namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
Expand All @@ -28,11 +27,11 @@ internal abstract class ServerApiCall : IServerAPICalls
public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCredential)
{
this.Repository = repository;

HttpClientHandler handler = new HttpClientHandler();
bool token = false;

if(networkCredential != null)
if(networkCredential != null)
{
token = String.Equals("token", networkCredential.UserName) ? true : false;
};
Expand All @@ -47,7 +46,7 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede
} else {

handler.Credentials = networkCredential;

_sessionClient = new HttpClient(handler);
};
_sessionClient.Timeout = TimeSpan.FromMinutes(10);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,10 +281,10 @@ Describe "Test Publish-PSResource" -tags 'CI' {

$results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Version $version
$results | Should -Not -BeNullOrEmpty
$results[0].Name | Should -Be $script:PublishModuleName
$results[0].Version | Should -Be $version
$results[0].Dependencies.Name | Should -Be $dependencyName
$results[0].Dependencies.VersionRange.MinVersion.ToString() | Should -Be $dependencyVersion
$results[0].Name | Should -Be $script:PublishModuleName
$results[0].Version | Should -Be $version
$results[0].Dependencies.Name | Should -Be $dependencyName
$results[0].Dependencies.VersionRange.MinVersion.ToString() | Should -Be $dependencyVersion
}

It "Publish a module with multiple dependencies" {
Expand All @@ -296,18 +296,18 @@ Describe "Test Publish-PSResource" -tags 'CI' {
# New-ModuleManifest requires that the module be installed before it can be added as a dependency
Install-PSResource -Name $dependency1Name -Repository $ACRRepoName -TrustRepository -Verbose -Reinstall
Install-PSResource -Name $dependency2Name -Version $dependency2Version -Repository $ACRRepoName -TrustRepository -Reinstall
New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" -RequiredModules @( $dependency1Name , @{ ModuleName = $dependency2Name; ModuleVersion = $dependency2Version })
New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" -RequiredModules @( $dependency1Name , @{ ModuleName = $dependency2Name; ModuleVersion = $dependency2Version })

Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName

$results = Find-PSResource -Name $script:PublishModuleName -Repository $ACRRepoName -Version $version
$results | Should -Not -BeNullOrEmpty
$results[0].Name | Should -Be $script:PublishModuleName
$results[0].Version | Should -Be $version
$results[0].Name | Should -Be $script:PublishModuleName
$results[0].Version | Should -Be $version
$results[0].Dependencies.Name | Should -Be $dependency1Name, $dependency2Name
$results[0].Dependencies.VersionRange.MinVersion.OriginalVersion.ToString() | Should -Be $dependency2Version
$results[0].Dependencies.VersionRange.MinVersion.OriginalVersion.ToString() | Should -Be $dependency2Version
}

It "Publish a module and clean up properly when file in module is readonly" {
$version = "13.0.0"
New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module"
Expand Down Expand Up @@ -498,4 +498,17 @@ Describe "Test Publish-PSResource" -tags 'CI' {

{Publish-PSResource -Path $psm1Path -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource"
}

It "Publish a module with -ModulePrefix" {
$version = "1.0.0"
$modulePrefix = "unlisted"
New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module"

Publish-PSResource -Path $script:PublishModuleBase -Repository $ACRRepoName -ModulePrefix $modulePrefix

$results = Find-PSResource -Name "$modulePrefix/$script:PublishModuleName" -Repository $ACRRepoName
$results | Should -Not -BeNullOrEmpty
$results[0].Name | Should -Be $script:PublishModuleName
$results[0].Version | Should -Be $version
}
}

0 comments on commit c9cec29

Please sign in to comment.