From 836b5a07244cbae128b8eb8ca33325e479ecd7f5 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Thu, 14 Jul 2022 16:17:29 -0700 Subject: [PATCH 01/15] Remove ShouldProcess in FindPSResource --- src/code/FindPSResource.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/code/FindPSResource.cs b/src/code/FindPSResource.cs index b99b520c5..6d01c9753 100644 --- a/src/code/FindPSResource.cs +++ b/src/code/FindPSResource.cs @@ -20,8 +20,7 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets /// [Cmdlet(VerbsCommon.Find, "PSResource", - DefaultParameterSetName = ResourceNameParameterSet, - SupportsShouldProcess = true)] + DefaultParameterSetName = ResourceNameParameterSet)] [OutputType(typeof(PSResourceInfo), typeof(PSCommandResourceInfo))] public sealed class FindPSResource : PSCmdlet { From 71331573ffd6e23166e6d3f0aad32e9273766a0f Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Fri, 15 Jul 2022 21:10:38 -0700 Subject: [PATCH 02/15] Add force parameter to Register-PSResourceRepository --- src/code/RegisterPSResourceRepository.cs | 11 ++++++++--- src/code/RepositorySettings.cs | 21 ++++++++++++++++++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 6564f4d18..ccd2a4d31 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -104,11 +104,16 @@ class RegisterPSResourceRepository : PSCmdlet public PSCredential ProxyCredential { get; set; } /// - /// When specified, displays the succcessfully registered repository and its information + /// When specified, displays the succcessfully registered repository and its information. /// [Parameter] public SwitchParameter PassThru { get; set; } - + + /// + /// When specified, will overwrite information for any existing repository with the same name. + /// + [Parameter] + public SwitchParameter Force { get; set; } #endregion #region Methods @@ -246,7 +251,7 @@ private PSRepositoryInfo AddToRepositoryStoreHelper(string repoName, Uri repoUri return null; } - return RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo); + return RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, Force); } private PSRepositoryInfo NameParameterSetHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index dec5d2d15..5f36af84f 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -60,7 +60,7 @@ public static void CheckRepositoryStore() // Add PSGallery to the newly created store Uri psGalleryUri = new Uri(PSGalleryRepoUri); - Add(PSGalleryRepoName, psGalleryUri, defaultPriority, defaultTrusted, repoCredentialInfo: null); + Add(PSGalleryRepoName, psGalleryUri, defaultPriority, defaultTrusted, repoCredentialInfo: null, force: false); } // Open file (which should exist now), if cannot/is corrupted then throw error @@ -79,7 +79,7 @@ public static void CheckRepositoryStore() /// Returns: PSRepositoryInfo containing information about the repository just added to the repository store /// /// - public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) + public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force) { try { @@ -87,7 +87,22 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit XDocument doc = LoadXDocument(FullRepositoryPath); if (FindRepositoryElement(doc, repoName) != null) { - throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); + if (!force) + { + throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); + } + + // Delete the existing repository before overwriting it (otherwire multiple repos with the same name will be added) + List removedRepositories = RepositorySettings.Remove(new string[] { repoName }, out string[] errorList); + + // Need to load the document again because of changes after removing + doc = LoadXDocument(FullRepositoryPath); + + if (errorList.Count() > 0) + { + throw new PSInvalidOperationException($"The PSResource Repository '{repoName}' cannot be overwritten: ${errorList.FirstOrDefault()}"); + } + } // Else, keep going From c61a5c1573644300d419f4ac021a662475517766 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 18 Jul 2022 15:36:39 -0700 Subject: [PATCH 03/15] Fix bugs introduced from changes --- src/code/RegisterPSResourceRepository.cs | 114 ++++++------- src/code/RepositorySettings.cs | 179 ++++++++++++++++++-- src/code/SetPSResourceRepository.cs | 119 +++++-------- test/RegisterPSResourceRepository.Tests.ps1 | 98 ++++++++++- test/SetPSResourceRepository.Tests.ps1 | 13 +- 5 files changed, 360 insertions(+), 163 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index ccd2a4d31..d204c8854 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -114,6 +114,7 @@ class RegisterPSResourceRepository : PSCmdlet /// [Parameter] public SwitchParameter Force { get; set; } + #endregion #region Methods @@ -146,9 +147,19 @@ protected override void ProcessRecord() ThrowTerminatingError(errorRecord); } + string[] errorMsgs; try { - items.Add(NameParameterSetHelper(Name, _uri, Priority, Trusted, CredentialInfo)); + items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, CredentialInfo, Force, this, out errorMsgs)); + + if (errorMsgs.Length > 0) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsgs[0]), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } } catch (Exception e) { @@ -205,71 +216,30 @@ protected override void ProcessRecord() } } - private PSRepositoryInfo AddToRepositoryStoreHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition - repoName = repoName.Trim(' '); - if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) - { - throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); - } - - if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) - { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); - } - - if (repoCredentialInfo != null) - { - bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, this); - - if (repoCredentialInfo.Credential != null) - { - if (!isSecretManagementModuleAvailable) - { - ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, - this)); - } - else - { - Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, this); - } - } - - if (!isSecretManagementModuleAvailable) - { - WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); - } - } - - WriteVerbose("All required values to add to repository provided, calling internal Add() API now"); - if (!ShouldProcess(repoName, "Register repository to repository store")) - { - return null; - } - - return RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, Force); - } - - private PSRepositoryInfo NameParameterSetHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) - { - WriteVerbose("Provided Name (NameParameterSet) but with invalid value of PSGallery"); - throw new ArgumentException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"); - } - - return AddToRepositoryStoreHelper(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo); - } private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repoTrusted) { Uri psGalleryUri = new Uri(PSGalleryRepoUri); WriteVerbose("(PSGallerySet) internal name and uri values for Add() API are hardcoded and validated, priority and trusted values, if passed in, also validated"); - return AddToRepositoryStoreHelper(PSGalleryRepoName, psGalleryUri, repoPriority, repoTrusted, repoCredentialInfo: null); + var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName, + psGalleryUri, + repoPriority, + repoTrusted, + repoCredentialInfo: null, + Force, + this, + out string[] errorMsgs); + + if (errorMsgs.Length > 0) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsgs[0]), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } + + return addedRepo; } private List RepositoriesParameterSetHelper() @@ -320,7 +290,7 @@ private List RepositoriesParameterSetHelper() private PSRepositoryInfo RepoValidationHelper(Hashtable repo) { - if (!repo.ContainsKey("Name") || String.IsNullOrEmpty(repo["Name"].ToString())) + if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrWhiteSpace(repo["Name"].ToString())) { WriteError(new ErrorRecord( new PSInvalidOperationException("Repository name cannot be null"), @@ -340,7 +310,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - if (!repo.ContainsKey("Uri") || String.IsNullOrEmpty(repo["Uri"].ToString())) + if (!repo.ContainsKey("Uri") || repo["Uri"] == null || String.IsNullOrEmpty(repo["Uri"].ToString())) { WriteError(new ErrorRecord( new PSInvalidOperationException("Repository Uri cannot be null"), @@ -373,11 +343,25 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { WriteVerbose(String.Format("(RepositoriesParameterSet): on repo: {0}. Registers Name based repository", repo["Name"])); - return NameParameterSetHelper(repo["Name"].ToString(), + var addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(), repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : defaultPriority, repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : defaultTrusted, - repoCredentialInfo); + repoCredentialInfo, + Force, + this, + out string[] errorMsgs); + + if (errorMsgs.Length > 0) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsgs[0]), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } + + return addedRepo; } catch (Exception e) { diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 5f36af84f..c091c1fb1 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -74,6 +74,149 @@ public static void CheckRepositoryStore() } } + public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + { + errorMsgs = new string[] { }; + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"); + } + + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); + } + + + public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + { + errorMsgs = new string[] { }; + List tempErrors = new List(); + // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition + repoName = repoName.Trim(' '); + if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) + { + throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); + } + + if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) + { + throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); + } + + if (repoCredentialInfo != null) + { + bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn); + + if (repoCredentialInfo.Credential != null) + { + if (!isSecretManagementModuleAvailable) + { + tempErrors.Add($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."); + } + else + { + Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn); + } + } + + if (!isSecretManagementModuleAvailable) + { + cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); + } + } + + errorMsgs = tempErrors.ToArray(); + if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store")) + { + return null; + } + + if (errorMsgs.Length > 0) + { + return null; + } + + var repo = RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force); + + return repo; + } + + + public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + { + var tempErrors = new List() { }; + + if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) + { + throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); + } + + // check repoName can't contain * or just be whitespace + // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition + repoName = repoName.Trim(); + if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) + { + throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); + } + + // check PSGallery Uri is not trying to be set + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null) + { + throw new ArgumentException("The PSGallery repository has a pre-defined Uri. Setting the -Uri parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); + } + + // check PSGallery CredentialInfo is not trying to be set + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null) + { + throw new ArgumentException("The PSGallery repository does not require authentication. Setting the -CredentialInfo parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); + } + + // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable) + bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?(); + + if (repoCredentialInfo != null) + { + bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn); + + if (repoCredentialInfo.Credential != null) + { + if (!isSecretManagementModuleAvailable) + { + tempErrors.Add($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."); + } + else + { + Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn); + } + } + + if (!isSecretManagementModuleAvailable) + { + cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); + } + } + + // determine if either 1 of 4 values are attempting to be set: Uri, Priority, Trusted, CredentialInfo. + // if none are (i.e only Name parameter was provided, write error) + if (repoUri == null && repoPriority == defaultPriority && _trustedNullable == null && repoCredentialInfo == null) + { + throw new ArgumentException("Either Uri, Priority, Trusted or CredentialInfo parameters must be requested to be set"); + } + + errorMsgs = tempErrors.ToArray(); + //WriteVerbose("All required values to set repository provided, calling internal Update() API now"); + if (!cmdletPassedIn.ShouldProcess(repoName, "Set repository's value(s) in repository store")) + { + return null; + } + + if (errorMsgs.Length > 0) + { + return null; + } + + return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); + } + /// /// Add a repository to the store /// Returns: PSRepositoryInfo containing information about the repository just added to the repository store @@ -87,20 +230,20 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit XDocument doc = LoadXDocument(FullRepositoryPath); if (FindRepositoryElement(doc, repoName) != null) { - if (!force) - { - throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); - } - - // Delete the existing repository before overwriting it (otherwire multiple repos with the same name will be added) - List removedRepositories = RepositorySettings.Remove(new string[] { repoName }, out string[] errorList); - - // Need to load the document again because of changes after removing + if (!force) + { + throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); + } + + // Delete the existing repository before overwriting it (otherwire multiple repos with the same name will be added) + List removedRepositories = RepositorySettings.Remove(new string[] { repoName }, out string[] errorList); + + // Need to load the document again because of changes after removing doc = LoadXDocument(FullRepositoryPath); - if (errorList.Count() > 0) - { - throw new PSInvalidOperationException($"The PSResource Repository '{repoName}' cannot be overwritten: ${errorList.FirstOrDefault()}"); + if (errorList.Count() > 0) + { + throw new PSInvalidOperationException($"The PSResource Repository '{repoName}' cannot be overwritten: ${errorList.FirstOrDefault()}"); } } @@ -141,8 +284,9 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit /// Updates a repository name, Uri, priority, installation policy, or credential information /// Returns: void /// - public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo) + public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { + errorMsgs = new string[] { }; PSRepositoryInfo updatedRepo; try { @@ -151,7 +295,14 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio XElement node = FindRepositoryElement(doc, repoName); if (node == null) { - throw new ArgumentException("Cannot find the repository because it does not exist. Try registering the repository using 'Register-PSResourceRepository'"); + if (!force) + { + throw new ArgumentException("Cannot find the repository because it does not exist. Try registering the repository using 'Register-PSResourceRepository'"); + } + + bool repoIsTrusted = repoTrusted == null || repoTrusted == false ? false : true; + repoPriority = repoPriority < 0 ? defaultPriority : repoPriority; + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); } // Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted. diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 2ada5bdee..a6060ff56 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -89,11 +89,17 @@ public SwitchParameter Trusted public PSCredentialInfo CredentialInfo { get; set; } /// - /// When specified, displays the successfully registered repository and its information + /// When specified, displays the successfully registered repository and its information. /// [Parameter] public SwitchParameter PassThru { get; set; } + /// + /// When specified, will register a new repository with information specified if one currently does not exist. + /// + [Parameter] + public SwitchParameter Force { get; set; } + #endregion #region Private methods @@ -121,7 +127,25 @@ protected override void ProcessRecord() case NameParameterSet: try { - items.Add(UpdateRepositoryStoreHelper(Name, _uri, Priority, Trusted, CredentialInfo)); + items.Add(RepositorySettings.UpdateRepositoryStore(Name, + _uri, + Priority, + Trusted, + isSet, + DefaultPriority, + CredentialInfo, + Force, + this, + out string[] errorMsgs)); + + if (errorMsgs.Length > 0) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsgs[0]), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } } catch (Exception e) { @@ -162,77 +186,6 @@ protected override void ProcessRecord() } } - private PSRepositoryInfo UpdateRepositoryStoreHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) - { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); - } - - // check repoName can't contain * or just be whitespace - // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition - repoName = repoName.Trim(); - if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) - { - throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); - } - - // check PSGallery Uri is not trying to be set - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null) - { - throw new ArgumentException("The PSGallery repository has a pre-defined Uri. Setting the -Uri parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); - } - - // check PSGallery CredentialInfo is not trying to be set - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null) - { - throw new ArgumentException("The PSGallery repository does not require authentication. Setting the -CredentialInfo parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); - } - - // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable) - bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?(); - - if (repoCredentialInfo != null) - { - bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, this); - - if (repoCredentialInfo.Credential != null) - { - if (!isSecretManagementModuleAvailable) - { - ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, - this)); - } - else - { - Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, this); - } - } - - if (!isSecretManagementModuleAvailable) - { - WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); - } - } - - // determine if either 1 of 4 values are attempting to be set: Uri, Priority, Trusted, CredentialInfo. - // if none are (i.e only Name parameter was provided, write error) - if (repoUri == null && repoPriority == DefaultPriority && _trustedNullable == null && repoCredentialInfo == null) - { - throw new ArgumentException("Either Uri, Priority, Trusted or CredentialInfo parameters must be requested to be set"); - } - - WriteVerbose("All required values to set repository provided, calling internal Update() API now"); - if (!ShouldProcess(repoName, "Set repository's value(s) in repository store")) - { - return null; - } - return RepositorySettings.Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo); - } - private List RepositoriesParameterSetHelper() { List reposUpdatedFromHashtable = new List(); @@ -305,11 +258,27 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { - return UpdateRepositoryStoreHelper(repo["Name"].ToString(), + var updatedRepo = RepositorySettings.UpdateRepositoryStore(repo["Name"].ToString(), repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, repoTrusted, - repoCredentialInfo); + isSet, + DefaultPriority, + repoCredentialInfo, + Force, + this, + out string[] errorMsgs); + + if (errorMsgs.Length > 0) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsgs[0]), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } + + return updatedRepo; } catch (Exception e) { diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index acaeca848..0cece8919 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -234,23 +234,94 @@ Describe "Test Register-PSResourceRepository" { $res3.Name | Should -Be $TestRepoName3 } - $testCases2 = @{Type = "-Name is not specified"; IncorrectHashTable = @{Uri = $tmpDir1Path}; ErrorId = "NullNameForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Name is PSGallery"; IncorrectHashTable = @{Name = $PSGalleryName; Uri = $tmpDir1Path}; ErrorId = "PSGalleryProvidedAsNameRepoPSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Uri not specified"; IncorrectHashTable = @{Name = $TestRepoName1}; ErrorId = "NullUriForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Uri is not valid scheme"; IncorrectHashTable = @{Name = $TestRepoName1; Uri="www.google.com"}; ErrorId = "InvalidUri,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"} + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Name is not specified" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Uri = $tmpDir1Path}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "NullNameForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 + + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Name is PSGallery" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $PSGalleryName; Uri = $tmpDir1Path}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "PSGalleryProvidedAsNameRepoPSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 - It "not register incorrectly formatted Name type repo among correct ones when incorrect type is " -TestCases $testCases2 { - param($Type, $IncorrectHashTable, $ErrorId) + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Uri not specified" { $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $TestRepoName1}; $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 Unregister-PSResourceRepository -Name $PSGalleryName Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "NullUriForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly $ErrorId + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 + + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Uri is not valid scheme" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $TestRepoName1; Uri="www.google.com"}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "InvalidUri,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId $res = Get-PSResourceRepository -Name $TestRepoName2 $res.Name | Should -Be $TestRepoName2 @@ -273,6 +344,17 @@ Describe "Test Register-PSResourceRepository" { $res.Priority | Should -Be 50 } + It "should update a repository if -Force is used" { + Register-PSResourceRepository -Name $TestRepoName1 -Uri "./" + Register-PSResourceRepository -Name $TestRepoName1 -Uri "./" -Priority 3 -Force + $res = Get-PSResourceRepository -Name $TestRepoName1 + + $res.Name | Should -Be $TestRepoName1 + $Res.Uri.LocalPath | Should -Contain $relativeCurrentPath + $res.Trusted | Should -Be False + $res.Priority | Should -Be 3 + } + It "should register local file share NuGet based repository" { Register-PSResourceRepository -Name "localFileShareTestRepo" -Uri "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" $res = Get-PSResourceRepository -Name "localFileShareTestRepo" @@ -290,7 +372,7 @@ Describe "Test Register-PSResourceRepository" { } It "throws error if CredentialInfo is passed in with Credential property without SecretManagement module setup" { - { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule" + { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res | Should -BeNullOrEmpty diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index 25eb1c820..ba169de39 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -241,6 +241,17 @@ Describe "Test Set-PSResourceRepository" { $Res.Uri.LocalPath | Should -Contain "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" } + It "set repository with -Force should register repository" { + $testRepoName = "NewForceTestRepo" + Set-PSResourceRepository -Name $testRepoName -Uri $tmpDir1Path -Force -PassThru + + $res = Get-PSResourceRepository -Name $testRepoName + $res.Name | Should -Be $testRepoName + $Res.Uri.LocalPath | Should -Contain $tmpDir1Path + $res.Priority | Should -Be 50 + $res.Trusted | Should -Be False + } + It "set repository and see updated repository with -PassThru" { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path $res = Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir2Path -PassThru @@ -263,7 +274,7 @@ Describe "Test Set-PSResourceRepository" { { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -CredentialInfo $credentialInfo2 - } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule" + } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res.CredentialInfo | Should -BeNullOrEmpty From 12a2aaa1a257fec0eaf474f6b8b42a1049961492 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Tue, 19 Jul 2022 19:12:21 -0700 Subject: [PATCH 04/15] Remove -Force param for Set-PSResourceRepository --- src/code/RepositorySettings.cs | 13 ++++--------- src/code/SetPSResourceRepository.cs | 8 -------- test/SetPSResourceRepository.Tests.ps1 | 4 ++-- 3 files changed, 6 insertions(+), 19 deletions(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index c091c1fb1..f5d0ef86b 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -141,7 +141,7 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri } - public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { var tempErrors = new List() { }; @@ -214,7 +214,7 @@ public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUr return null; } - return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); + return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, cmdletPassedIn, out errorMsgs); } /// @@ -284,7 +284,7 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit /// Updates a repository name, Uri, priority, installation policy, or credential information /// Returns: void /// - public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { errorMsgs = new string[] { }; PSRepositoryInfo updatedRepo; @@ -295,14 +295,9 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio XElement node = FindRepositoryElement(doc, repoName); if (node == null) { - if (!force) - { - throw new ArgumentException("Cannot find the repository because it does not exist. Try registering the repository using 'Register-PSResourceRepository'"); - } - bool repoIsTrusted = repoTrusted == null || repoTrusted == false ? false : true; repoPriority = repoPriority < 0 ? defaultPriority : repoPriority; - return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsgs); } // Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted. diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index a6060ff56..27636809e 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -94,12 +94,6 @@ public SwitchParameter Trusted [Parameter] public SwitchParameter PassThru { get; set; } - /// - /// When specified, will register a new repository with information specified if one currently does not exist. - /// - [Parameter] - public SwitchParameter Force { get; set; } - #endregion #region Private methods @@ -134,7 +128,6 @@ protected override void ProcessRecord() isSet, DefaultPriority, CredentialInfo, - Force, this, out string[] errorMsgs)); @@ -265,7 +258,6 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) isSet, DefaultPriority, repoCredentialInfo, - Force, this, out string[] errorMsgs); diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index ba169de39..aae4edd38 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -241,9 +241,9 @@ Describe "Test Set-PSResourceRepository" { $Res.Uri.LocalPath | Should -Contain "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" } - It "set repository with -Force should register repository" { + It "set repository should register repository if it does not already exist" { $testRepoName = "NewForceTestRepo" - Set-PSResourceRepository -Name $testRepoName -Uri $tmpDir1Path -Force -PassThru + Set-PSResourceRepository -Name $testRepoName -Uri $tmpDir1Path -PassThru $res = Get-PSResourceRepository -Name $testRepoName $res.Name | Should -Be $testRepoName From a1cf47b4ce4f20b832097aa6cbaea4902d21d0c7 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 17:43:57 -0700 Subject: [PATCH 05/15] Update test/RegisterPSResourceRepository.Tests.ps1 Co-authored-by: Anam Navied --- test/RegisterPSResourceRepository.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 0cece8919..7b2e54c45 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -259,7 +259,7 @@ Describe "Test Register-PSResourceRepository" { $res3.Priority | Should -Be 30 } - It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Name is PSGallery" { + It "not register incorrectly formatted -Name type repo among correct ones, where incorrect type has -Name of PSGallery" { $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} $correctHashtable3 = @{PSGallery = $True; Priority = 30}; From 12b54fddf53078cbcc37652c3295389edde3678a Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 17:45:08 -0700 Subject: [PATCH 06/15] Update src/code/RepositorySettings.cs Co-authored-by: Anam Navied --- src/code/RepositorySettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index f5d0ef86b..9d31abff9 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -286,7 +286,7 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit /// public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { - errorMsgs = new string[] { }; + errorMsgs = Utils.EmptyStrArray; PSRepositoryInfo updatedRepo; try { From 9a04a3fe5d439b04c51d6596195e37af676ffd17 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 17:55:15 -0700 Subject: [PATCH 07/15] Update src/code/RepositorySettings.cs Co-authored-by: Anam Navied --- src/code/RepositorySettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 9d31abff9..c9be19b9d 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -76,7 +76,7 @@ public static void CheckRepositoryStore() public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { - errorMsgs = new string[] { }; + errorMsgs = Utils.EmptyStrArray; if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"); From eb6dcb163bbd7513996fd57a3faa2449241cd09a Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 17:55:34 -0700 Subject: [PATCH 08/15] Update src/code/RepositorySettings.cs Co-authored-by: Anam Navied --- src/code/RepositorySettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index c9be19b9d..b6816c152 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -88,7 +88,7 @@ public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int r public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { - errorMsgs = new string[] { }; + errorMsgs = Utils.EmptyStrArray; List tempErrors = new List(); // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition repoName = repoName.Trim(' '); From ade7f843cda906478c0187cefa7b683811f81dbe Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 17:58:21 -0700 Subject: [PATCH 09/15] Update src/code/RepositorySettings.cs Co-authored-by: Anam Navied --- src/code/RepositorySettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index b6816c152..a547b3897 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -295,7 +295,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio XElement node = FindRepositoryElement(doc, repoName); if (node == null) { - bool repoIsTrusted = repoTrusted == null || repoTrusted == false ? false : true; + bool repoIsTrusted = !(repoTrusted == null || repoTrusted == false); repoPriority = repoPriority < 0 ? defaultPriority : repoPriority; return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsgs); } From 0a1ebd059f8410fb8da5edd22c6feefdd52265f5 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 20 Jul 2022 18:06:25 -0700 Subject: [PATCH 10/15] Update test/RegisterPSResourceRepository.Tests.ps1 Co-authored-by: Anam Navied --- test/RegisterPSResourceRepository.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 7b2e54c45..5d30a93f3 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -234,7 +234,7 @@ Describe "Test Register-PSResourceRepository" { $res3.Name | Should -Be $TestRepoName3 } - It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Name is not specified" { + It "not register incorrectly formatted -Name type repo among correct ones, where incorrect one is missing -Name" { $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} $correctHashtable3 = @{PSGallery = $True; Priority = 30}; From d9581ee65fd6b250c94aa04a3018b61950f64be8 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Wed, 10 Aug 2022 17:37:00 -0700 Subject: [PATCH 11/15] Update src/code/RepositorySettings.cs Co-authored-by: Anam Navied --- src/code/RepositorySettings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index a547b3897..5b4370dcc 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -143,7 +143,7 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) { - var tempErrors = new List() { }; + var tempErrors = new List(); if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) { From ac18b035ed58a0928fe708d5cce9060cb5c07345 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Thu, 11 Aug 2022 00:04:26 -0700 Subject: [PATCH 12/15] Refactor errors --- src/code/RegisterPSResourceRepository.cs | 19 +++--- src/code/RepositorySettings.cs | 73 +++++++++++++----------- src/code/SetPSResourceRepository.cs | 12 ++-- 3 files changed, 56 insertions(+), 48 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index d204c8854..e2279b807 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -147,15 +147,14 @@ protected override void ProcessRecord() ThrowTerminatingError(errorRecord); } - string[] errorMsgs; try { - items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, CredentialInfo, Force, this, out errorMsgs)); + items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, CredentialInfo, Force, this, out string errorMsg)); - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException(errorMsgs[0]), + new PSInvalidOperationException(errorMsg), "RepositoryCredentialSecretManagementUnavailableModule", ErrorCategory.ResourceUnavailable, this)); @@ -228,12 +227,12 @@ private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repo repoCredentialInfo: null, Force, this, - out string[] errorMsgs); + out string errorMsg); - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException(errorMsgs[0]), + new PSInvalidOperationException(errorMsg), "RepositoryCredentialSecretManagementUnavailableModule", ErrorCategory.ResourceUnavailable, this)); @@ -350,12 +349,12 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) repoCredentialInfo, Force, this, - out string[] errorMsgs); + out string errorMsg); - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException(errorMsgs[0]), + new PSInvalidOperationException(errorMsg), "RepositoryCredentialSecretManagementUnavailableModule", ErrorCategory.ResourceUnavailable, this)); diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 5b4370dcc..6f101c16b 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -74,22 +74,22 @@ public static void CheckRepositoryStore() } } - public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg) { - errorMsgs = Utils.EmptyStrArray; + errorMsg = String.Empty; if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) { - throw new ArgumentException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"); + errorMsg = "Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"; + return null; } - return AddToRepositoryStore(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsgs); + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsg); } - public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg) { - errorMsgs = Utils.EmptyStrArray; - List tempErrors = new List(); + errorMsg = string.Empty; // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition repoName = repoName.Trim(' '); if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) @@ -99,7 +99,8 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); + errorMsg = "Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"; + return null; } if (repoCredentialInfo != null) @@ -110,7 +111,8 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri { if (!isSecretManagementModuleAvailable) { - tempErrors.Add($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."); + errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."; + return null; } else { @@ -124,13 +126,12 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri } } - errorMsgs = tempErrors.ToArray(); if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store")) { return null; } - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { return null; } @@ -141,13 +142,13 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri } - public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string errorMsg) { - var tempErrors = new List(); - + errorMsg = string.Empty; if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); + errorMsg = "Invalid Uri, Uri must be one of the following schemes: HTTPS, HTTP, FTP, File Based"; + return null; } // check repoName can't contain * or just be whitespace @@ -155,19 +156,22 @@ public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUr repoName = repoName.Trim(); if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) { - throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); + errorMsg = "Name cannot be null or empty, or contain wildcards"; + return null; } // check PSGallery Uri is not trying to be set if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null) { - throw new ArgumentException("The PSGallery repository has a pre-defined Uri. Setting the -Uri parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); + errorMsg = "The PSGallery repository has a predefined Uri. Setting the -Uri parameter for this repository is not allowed. Please run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery."; + return null; } // check PSGallery CredentialInfo is not trying to be set if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null) { - throw new ArgumentException("The PSGallery repository does not require authentication. Setting the -CredentialInfo parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); + errorMsg = "Setting the -CredentialInfo parameter for PSGallery is not allowed. Run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery."; + return null; } // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable) @@ -181,7 +185,8 @@ public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUr { if (!isSecretManagementModuleAvailable) { - tempErrors.Add($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."); + errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."; + return null; } else { @@ -199,22 +204,21 @@ public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUr // if none are (i.e only Name parameter was provided, write error) if (repoUri == null && repoPriority == defaultPriority && _trustedNullable == null && repoCredentialInfo == null) { - throw new ArgumentException("Either Uri, Priority, Trusted or CredentialInfo parameters must be requested to be set"); + errorMsg = "Must set Uri, Priority, Trusted or CredentialInfo parameter"; + return null; } - errorMsgs = tempErrors.ToArray(); - //WriteVerbose("All required values to set repository provided, calling internal Update() API now"); if (!cmdletPassedIn.ShouldProcess(repoName, "Set repository's value(s) in repository store")) { return null; } - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { return null; } - return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, cmdletPassedIn, out errorMsgs); + return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, cmdletPassedIn, out errorMsg); } /// @@ -284,9 +288,9 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit /// Updates a repository name, Uri, priority, installation policy, or credential information /// Returns: void /// - public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string[] errorMsgs) + public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string errorMsg) { - errorMsgs = Utils.EmptyStrArray; + errorMsg = string.Empty; PSRepositoryInfo updatedRepo; try { @@ -297,7 +301,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio { bool repoIsTrusted = !(repoTrusted == null || repoTrusted == false); repoPriority = repoPriority < 0 ? defaultPriority : repoPriority; - return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsgs); + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsg); } // Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted. @@ -305,19 +309,22 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio if (node.Attribute("Priority") == null) { - throw new ArgumentException("Repository element does not contain neccessary 'Priority' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Priority' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } if (node.Attribute("Trusted") == null) { - throw new ArgumentException("Repository element does not contain neccessary 'Trusted' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Trusted' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } bool urlAttributeExists = node.Attribute("Url") != null; bool uriAttributeExists = node.Attribute("Uri") != null; if (!urlAttributeExists && !uriAttributeExists) { - throw new ArgumentException("Repository element does not contain neccessary 'Url' attribute (or alternatively 'Uri' attribute), in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Url' attribute (or alternatively 'Uri' attribute), in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } // Else, keep going @@ -337,7 +344,8 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio // Create Uri from node Uri attribute to create PSRepositoryInfo item to return. if (!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl)) { - throw new PSInvalidOperationException(String.Format("Unable to read incorrectly formatted Url for repo {0}", repoName)); + errorMsg = $"Unable to read incorrectly formatted Url for repo {repoName}"; + return null; } } else @@ -346,7 +354,8 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio node.Attribute("Uri").Value = repoUri.AbsoluteUri; if (!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl)) { - throw new PSInvalidOperationException(String.Format("Unable to read incorrectly formatted Uri for repo {0}", repoName)); + errorMsg = $"Unable to read incorrectly formatted Uri for repo {repoName}"; + return null; } } } diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 27636809e..74f244ff1 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -129,12 +129,12 @@ protected override void ProcessRecord() DefaultPriority, CredentialInfo, this, - out string[] errorMsgs)); + out string errorMsg)); - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException(errorMsgs[0]), + new PSInvalidOperationException(errorMsg), "RepositoryCredentialSecretManagementUnavailableModule", ErrorCategory.ResourceUnavailable, this)); @@ -259,12 +259,12 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) DefaultPriority, repoCredentialInfo, this, - out string[] errorMsgs); + out string errorMsg); - if (errorMsgs.Length > 0) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException(errorMsgs[0]), + new PSInvalidOperationException(errorMsg), "RepositoryCredentialSecretManagementUnavailableModule", ErrorCategory.ResourceUnavailable, this)); From 15f9b383b4b670458ada7a46297e853157b77088 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Fri, 12 Aug 2022 16:01:32 -0700 Subject: [PATCH 13/15] Update exception handling --- src/code/SetPSResourceRepository.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 74f244ff1..1b0d7184b 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -135,8 +135,8 @@ protected override void ProcessRecord() { ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(errorMsg), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, + "ErrorInNameParameterSet", + ErrorCategory.InvalidArgument, this)); } } From 5c255258bcabc62d06c09c58c474e00991cda904 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Fri, 12 Aug 2022 16:14:12 -0700 Subject: [PATCH 14/15] Fix typos --- src/code/RegisterPSResourceRepository.cs | 4 ++-- src/code/RepositorySettings.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 104121c65..e38463f59 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -345,8 +345,8 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) WriteVerbose(String.Format("(RepositoriesParameterSet): on repo: {0}. Registers Name based repository", repo["Name"])); var addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(), repoUri, - repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : defaultPriority, - repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : defaultTrusted, + repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, + repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : DefaultTrusted, repoCredentialInfo, Force, this, diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 1ca0fde90..47c6185d5 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -60,7 +60,7 @@ public static void CheckRepositoryStore() // Add PSGallery to the newly created store Uri psGalleryUri = new Uri(PSGalleryRepoUri); - Add(PSGalleryRepoName, psGalleryUri, defaultPriority, defaultTrusted, repoCredentialInfo: null, force: false); + Add(PSGalleryRepoName, psGalleryUri, DefaultPriority, DefaultTrusted, repoCredentialInfo: null, force: false); } // Open file (which should exist now), if cannot/is corrupted then throw error @@ -300,7 +300,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio if (node == null) { bool repoIsTrusted = !(repoTrusted == null || repoTrusted == false); - repoPriority = repoPriority < 0 ? defaultPriority : repoPriority; + repoPriority = repoPriority < 0 ? DefaultPriority : repoPriority; return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsg); } From d5a38c58a757238534304fa23faece31063aa7d1 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Sat, 13 Aug 2022 23:41:49 -0700 Subject: [PATCH 15/15] Update errors and fix tests --- src/code/RegisterPSResourceRepository.cs | 6 +++--- src/code/SetPSResourceRepository.cs | 6 +++--- test/RegisterPSResourceRepository.Tests.ps1 | 2 +- test/SetPSResourceRepository.Tests.ps1 | 10 +++++----- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index e38463f59..871be13e3 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -156,8 +156,8 @@ protected override void ProcessRecord() { ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(errorMsg), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, + "ErrorInNameParameterSet", + ErrorCategory.InvalidArgument, this)); } } @@ -356,7 +356,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) { ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(errorMsg), - "RepositoryCredentialSecretManagementUnavailableModule", + "RegisterRepositoryError", ErrorCategory.ResourceUnavailable, this)); } diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 7bbda7e4d..7f874a56e 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -263,10 +263,10 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) if (!string.IsNullOrEmpty(errorMsg)) { - ThrowTerminatingError(new ErrorRecord( + WriteError(new ErrorRecord( new PSInvalidOperationException(errorMsg), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, + "ErrorSettingRepository", + ErrorCategory.InvalidData, this)); } diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 5d30a93f3..4853495ac 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -372,7 +372,7 @@ Describe "Test Register-PSResourceRepository" { } It "throws error if CredentialInfo is passed in with Credential property without SecretManagement module setup" { - { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res | Should -BeNullOrEmpty diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index 19129e124..cc8661258 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -109,8 +109,8 @@ Describe "Test Set-PSResourceRepository" { {Set-PSResourceRepository -Name $Name -Priority 25 -ErrorAction Stop} | Should -Throw -ErrorId "$ErrorId,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" } - $testCases2 = @{Type = "contains *"; Name = "test*Repository2"; ErrorId = "ErrorSettingIndividualRepoFromRepositories"}, - @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorSettingIndividualRepoFromRepositories"}, + $testCases2 = @{Type = "contains *"; Name = "test*Repository2"; ErrorId = "ErrorSettingRepository"}, + @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorSettingRepository"}, @{Type = "is null"; Name = $null; ErrorId = "NullNameForRepositoriesParameterSetRepo"} It "not set repository and write error given Name (RepositoriesParameterSet)" -TestCases $testCases2 { param($Type, $Name, $ErrorId) @@ -205,7 +205,7 @@ Describe "Test Set-PSResourceRepository" { Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingIndividualRepoFromRepositories,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingRepository,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 $Res.Uri.LocalPath | Should -Contain $tmpDir1Path @@ -235,7 +235,7 @@ Describe "Test Set-PSResourceRepository" { Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingIndividualRepoFromRepositories,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingRepository,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 $Res.Uri.LocalPath | Should -Contain $tmpDir1Path @@ -285,7 +285,7 @@ Describe "Test Set-PSResourceRepository" { { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -CredentialInfo $credentialInfo2 - } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" + } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res.CredentialInfo | Should -BeNullOrEmpty