From 559a6451d5d36e19ec45bc0c4f5ec0c21b3b5b07 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Fri, 23 Jul 2021 14:26:54 -0400 Subject: [PATCH 01/16] change URI creation, tests are broken --- .vscode/launch.json | 2 +- src/code/InstallHelper.cs | 5 +- src/code/RegisterPSResourceRepository.cs | 79 ++++++++++++++++----- src/code/Utils.cs | 39 ++++++++++ test/RegisterPSResourceRepository.Tests.ps1 | 11 ++- 5 files changed, 112 insertions(+), 24 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 036014deb..ab4404aaf 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -27,7 +27,7 @@ "name": ".NET Core Attach", "type": "coreclr", "request": "attach", - "processId": "${command:pickProcess}" + "processId": "195" } ] } \ No newline at end of file diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 1679c06fa..648d77462 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -347,7 +347,10 @@ private List InstallPackage(IEnumerable pkgsToInstall, s } catch (Exception e) { - _cmdletPassedIn.WriteDebug(string.Format("Error attempting download: '{0}'", e.Message)); + var message = string.Format("Error attempting download: '{0}'", e.Message); + var ex = new ArgumentException(message); + var installException = new ErrorRecord(ex, "InstallDownloadException", ErrorCategory.InvalidResult , null); + _cmdletPassedIn.WriteError(installException); } finally { diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index a31c110a8..d59822873 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -51,25 +51,34 @@ class RegisterPSResourceRepository : PSCmdlet /// [Parameter(Mandatory = true, Position = 1, ParameterSetName = NameParameterSet)] [ValidateNotNullOrEmpty] - public Uri URL - { - get - { return _url; } - - set - { - if (!Uri.TryCreate(value, string.Empty, out Uri url)) - { - var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", value); - var ex = new ArgumentException(message); - var moduleManifestNotFound = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); - ThrowTerminatingError(moduleManifestNotFound); - } + public string URL { get; set; } + + // /// + // /// Specifies the location of the repository to be registered. + // /// + // [Parameter(Mandatory = true, Position = 1, ParameterSetName = NameParameterSet)] + // [ValidateNotNullOrEmpty] + // public Uri URL { + // get + // { return _url; } + + // set + // { + // string urlString = SessionState.Path.GetResolvedPSPathFromPSPath(value.AbsoluteUri)[0].Path; + // // tryCreateResult = Uri.TryCreate(url, UriKind.Absolute, out _url); + + // if (!Uri.TryCreate(urlString, UriKind.Absolute, out Uri url)) + // { + // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", value); + // var ex = new ArgumentException(message); + // var moduleManifestNotFound = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); + // ThrowTerminatingError(moduleManifestNotFound); + // } + + // _url = url; + // } + // } - _url = url; - } - } - private Uri _url; /// /// When specified, registers PSGallery repository. @@ -124,9 +133,41 @@ public Uri URL #endregion #region Methods + private Uri _url; protected override void BeginProcessing() { + string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); + if (!tryCreateResult || _url == null) + { + WriteWarning("url creation failed!"); + ThrowTerminatingError(errorRecord); + } + + + + // bool tryCreateResult = false; + // try + // { + // tryCreateResult = Uri.TryCreate(url, UriKind.Absolute, out _url); + // } + // catch (Exception e) + // { + // var message = string.Format("Uri.TryCreate on provided Url threw error: " + e.Message); + // var ex = new ArgumentException(message); + // var tryCreateFailure = new ErrorRecord(ex, "TryCreateFails", ErrorCategory.InvalidArgument, null); + // ThrowTerminatingError(tryCreateFailure); + // } + + // if (!tryCreateResult) + // { + // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", url); + // var ex = new ArgumentException(message); + // var moduleManifestNotFound = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); + // ThrowTerminatingError(moduleManifestNotFound); + // } + if (Proxy != null || ProxyCredential != null) { ThrowTerminatingError(new ErrorRecord( @@ -158,7 +199,7 @@ protected override void ProcessRecord() case NameParameterSet: try { - items.Add(NameParameterSetHelper(Name, URL, Priority, Trusted)); + items.Add(NameParameterSetHelper(Name, _url, Priority, Trusted)); } catch (Exception e) { diff --git a/src/code/Utils.cs b/src/code/Utils.cs index b36e80130..5ce224c0f 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -11,6 +11,7 @@ using System.Management.Automation.Language; using System.Runtime.InteropServices; using NuGet.Versioning; +using System.Globalization; namespace Microsoft.PowerShell.PowerShellGet.UtilClasses { @@ -172,6 +173,44 @@ public static bool TryParseVersionOrVersionRange( } #endregion + + #region Url methods + public static bool CreateUrl( + string urlString, + out Uri urlResult, + out ErrorRecord errorRecord + ) + { + // string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + bool tryCreateResult = false; + try + { + tryCreateResult = Uri.TryCreate(urlString, UriKind.Absolute, out urlResult); + } + catch (Exception e) + { + var message = string.Format("Uri.TryCreate on provided Url string: " + urlString + " threw error: " + e.Message); + var ex = new ArgumentException(message); + errorRecord = new ErrorRecord(ex, "TryCreateFails", ErrorCategory.InvalidArgument, null); + urlResult = null; + return false; + } + + if (!tryCreateResult) + { + var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", urlString); + var ex = new ArgumentException(message); + errorRecord = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); + urlResult = null; + return false; + } + + // otherwise Url (urlResult) was successfully created in Uri.TryCreate() call + errorRecord = null; + return tryCreateResult; + + } + #endregion #region Path methods diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 58c1e4c90..9c971b1e8 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -26,7 +26,12 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL (bare minimum for NameParmaterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + Write-Host "$([regex]::Escape($tmpDir1Path))" + Write-Host $tmpDir1Path + Write-Host $res.URL + $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" + # "$([regex]::Escape($tmpDir1Path))" | Should -Contain $res.URL + $res.Trusted | Should -Be False $res.Priority | Should -Be 50 } @@ -34,7 +39,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository with Name, URL, Trusted (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL | Should -Match $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 50 } @@ -42,7 +47,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL, Trusted, Priority (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -Priority 20 -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL | Should -Match $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 20 } From 8f2cf579897d93bed96983155982d990119975e7 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Fri, 23 Jul 2021 15:34:03 -0400 Subject: [PATCH 02/16] fix url creation for PSGalleryParameterSet --- src/code/RegisterPSResourceRepository.cs | 17 +++++++---------- test/RegisterPSResourceRepository.Tests.ps1 | 6 +++++- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index d59822873..6e678c352 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -137,16 +137,6 @@ class RegisterPSResourceRepository : PSCmdlet protected override void BeginProcessing() { - string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; - bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); - if (!tryCreateResult || _url == null) - { - WriteWarning("url creation failed!"); - ThrowTerminatingError(errorRecord); - } - - - // bool tryCreateResult = false; // try // { @@ -197,6 +187,13 @@ protected override void ProcessRecord() switch (ParameterSetName) { case NameParameterSet: + string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); + if (!tryCreateResult || _url == null) + { + WriteWarning("url creation failed!"); + ThrowTerminatingError(errorRecord); + } try { items.Add(NameParameterSetHelper(Name, _url, Priority, Trusted)); diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 9c971b1e8..eed3aeba2 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -30,6 +30,7 @@ Describe "Test Register-PSResourceRepository" { Write-Host $tmpDir1Path Write-Host $res.URL $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" + # $res.URL | Should -Not -Contain $tmpDir1Path # "$([regex]::Escape($tmpDir1Path))" | Should -Contain $res.URL $res.Trusted | Should -Be False @@ -39,7 +40,10 @@ Describe "Test Register-PSResourceRepository" { It "register repository with Name, URL, Trusted (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Match $tmpDir1Path + Write-Host "$([regex]::Escape($tmpDir1Path))" + Write-Host $tmpDir1Path + Write-Host $res.URL + $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 50 } From 84fe368d2e1cc4c5de0ff8169362beba4c6a3376 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Mon, 26 Jul 2021 11:02:06 -0400 Subject: [PATCH 03/16] tests still broken but push changes --- src/code/RegisterPSResourceRepository.cs | 54 ++++++++++++++++++--- test/RegisterPSResourceRepository.Tests.ps1 | 15 ++++-- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 6e678c352..b8ca8336d 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -187,13 +187,19 @@ protected override void ProcessRecord() switch (ParameterSetName) { case NameParameterSet: - string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + string url = URL; + if (!URL.StartsWith(Uri.UriSchemeHttp) && !URL.StartsWith(Uri.UriSchemeHttps) && !URL.StartsWith(Uri.UriSchemeFtp)) + { + url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + } + bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); + if (!tryCreateResult || _url == null) { - WriteWarning("url creation failed!"); ThrowTerminatingError(errorRecord); } + try { items.Add(NameParameterSetHelper(Name, _url, Priority, Trusted)); @@ -372,16 +378,48 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - if (!Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out Uri repoURL)) + // string url = repo["Url"].ToString(); + + // if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && + // !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && + // !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) + // { + // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; + // } + + // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); + + // if (!tryCreateResult || repoURL == null) + // { + // WriteError(errorRecord); + // return null; + // } + + + string url = repo["Url"].ToString(); + if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) { - WriteError(new ErrorRecord( - new PSInvalidOperationException("Invalid url, unable to create"), - "InvalidUrlScheme", - ErrorCategory.InvalidArgument, - this)); + url = SessionState.Path.GetResolvedPSPathFromPSPath(repo["Url"].ToString())[0].Path; + } + + bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); + + if (!tryCreateResult || repoURL == null) + { + WriteError(errorRecord); return null; } + // if (!Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out Uri repoURL)) + // { + // WriteError(new ErrorRecord( + // new PSInvalidOperationException("Invalid url, unable to create"), + // "InvalidUrlScheme", + // ErrorCategory.InvalidArgument, + // this)); + // return null; + // } + try { WriteDebug(String.Format("(RepositoriesParameterSet): on repo: {0}. Registers Name based repository", repo["Name"])); diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index eed3aeba2..2907cfd6c 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -23,14 +23,21 @@ Describe "Test Register-PSResourceRepository" { Get-RemoveTestDirs($tmpDirPaths) } + It "should work on Windows and Linux" { + $resURL = "file:///tmp/testAnam/tmpDir1" + $tmpDirPath10 = "/tmp/testAnam/tmpDir1" + + $resURL | Should -Contain $tmpDirPath10 + } + It "register repository given Name, URL (bare minimum for NameParmaterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -PassThru $res.Name | Should -Be "testRepository" Write-Host "$([regex]::Escape($tmpDir1Path))" Write-Host $tmpDir1Path Write-Host $res.URL - $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" - # $res.URL | Should -Not -Contain $tmpDir1Path + # $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" + $res.URL | Should -Contain $tmpDir1Path # "$([regex]::Escape($tmpDir1Path))" | Should -Contain $res.URL $res.Trusted | Should -Be False @@ -51,7 +58,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL, Trusted, Priority (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -Priority 20 -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Match $tmpDir1Path + $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 20 } @@ -148,7 +155,7 @@ Describe "Test Register-PSResourceRepository" { } It "not register repository when Name is provided but URL is not" { - {Register-PSResourceRepository -Name "testRepository" -URL "" -ErrorAction Stop} | Should -Throw -ErrorId "InvalidUrl,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + {Register-PSResourceRepository -Name "testRepository" -URL "" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" } It "not register repository when Name is empty but URL is provided" { From 63e1cd6c4eabe66930aaf07afc89fc9015e269ce Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Mon, 26 Jul 2021 20:33:53 -0400 Subject: [PATCH 04/16] this works for all tests Linux and Windows and for relative paths --- nuget.config | 3 +- src/code/RegisterPSResourceRepository.cs | 150 +++++++++++++++----- src/code/Utils.cs | 19 +++ test/RegisterPSResourceRepository.Tests.ps1 | 38 ++--- 4 files changed, 156 insertions(+), 54 deletions(-) diff --git a/nuget.config b/nuget.config index 654858614..2029fc205 100644 --- a/nuget.config +++ b/nuget.config @@ -1,8 +1,9 @@ - + + diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index b8ca8336d..596d67125 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -137,27 +137,6 @@ class RegisterPSResourceRepository : PSCmdlet protected override void BeginProcessing() { - // bool tryCreateResult = false; - // try - // { - // tryCreateResult = Uri.TryCreate(url, UriKind.Absolute, out _url); - // } - // catch (Exception e) - // { - // var message = string.Format("Uri.TryCreate on provided Url threw error: " + e.Message); - // var ex = new ArgumentException(message); - // var tryCreateFailure = new ErrorRecord(ex, "TryCreateFails", ErrorCategory.InvalidArgument, null); - // ThrowTerminatingError(tryCreateFailure); - // } - - // if (!tryCreateResult) - // { - // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", url); - // var ex = new ArgumentException(message); - // var moduleManifestNotFound = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); - // ThrowTerminatingError(moduleManifestNotFound); - // } - if (Proxy != null || ProxyCredential != null) { ThrowTerminatingError(new ErrorRecord( @@ -188,17 +167,26 @@ protected override void ProcessRecord() { case NameParameterSet: string url = URL; - if (!URL.StartsWith(Uri.UriSchemeHttp) && !URL.StartsWith(Uri.UriSchemeHttps) && !URL.StartsWith(Uri.UriSchemeFtp)) + /*** trying to get it working */ + bool isUrlValid = TryCreateURL(url, out _url, out ErrorRecord errorRecord); + if (!isUrlValid) { - url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; + ThrowTerminatingError(errorRecord); } - bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); + /** WORKS */ + // bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); - if (!tryCreateResult || _url == null) - { - ThrowTerminatingError(errorRecord); - } + // if (!tryCreateResult || _url == null) + // { + // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; + // bool tryWithResolvedPath = Utils.CreateUrl(url, out _url, out errorRecord); + // if (!tryWithResolvedPath || _url == null) + // { + // ThrowTerminatingError(errorRecord); + // } + // WriteVerbose(url); + // } try { @@ -396,20 +384,72 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) // } - string url = repo["Url"].ToString(); - if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) - { - url = SessionState.Path.GetResolvedPSPathFromPSPath(repo["Url"].ToString())[0].Path; - } + // string url = repo["Url"].ToString(); + // if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) + // { + // url = SessionState.Path.GetResolvedPSPathFromPSPath(repo["Url"].ToString())[0].Path; + // } - bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); + // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); - if (!tryCreateResult || repoURL == null) + // if (!tryCreateResult || repoURL == null) + // { + // WriteError(errorRecord); + // return null; + // } + + string url = repo["Url"].ToString(); + /*** trying to get working */ + bool isUrlValid = TryCreateURL(repo["Url"].ToString(), out Uri repoURL, out ErrorRecord errorRecord); + if (!isUrlValid) { WriteError(errorRecord); return null; } + + + /** WORKS */ + // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); + + // if (!tryCreateResult || repoURL == null) + // { + // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; + // bool tryWithResolvedPath = Utils.CreateUrl(url, out repoURL, out errorRecord); + // if (!tryWithResolvedPath || repoURL == null) + // { + // WriteError(errorRecord); + // } + // WriteVerbose(url); + // } + + + // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); + + // if (!tryCreateResult || repoURL == null) + // { + // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; + // bool tryWithResolvedPath = Utils.CreateUrl(url, out repoURL, out errorRecord); + // if (!tryWithResolvedPath || repoURL == null) + // { + // WriteError(errorRecord); + // } + // WriteVerbose(url); + // } + + // bool tryCreateResult = Utils.CreateValidUrl(repo["Url"].ToString(), out Uri repoURL, out ErrorRecord errorRecord); + // // add condition repoURL == null (as a OR) + // if (!tryCreateResult) + // { + // WriteError(errorRecord); + // return null; + // } + // if (!tryCreateResult || repoURL == null) + // { + // WriteError(errorRecord); + // return null; + // } + // if (!Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out Uri repoURL)) // { // WriteError(new ErrorRecord( @@ -448,6 +488,46 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } } + private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRecord) + { + // create with url string as is + bool isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); + + // // only if url creation fails, try to convert url from possibly relative path to absolute path and try again + // if (!isUrlValid && !Utils.CreateUrl(SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path, out url, out errorRecord)) + // { + // return false; + // } + + // only if url creation fails, try to convert url from possibly relative path to absolute path and try again + if (!isUrlValid && (!urlString.StartsWith(Uri.UriSchemeHttp) && + !urlString.StartsWith(Uri.UriSchemeHttps) && + !urlString.StartsWith(Uri.UriSchemeFtp))) + { + try + { + string resolvedUrlString = SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; + urlString = resolvedUrlString; + } + catch (Exception e) + { + // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", urlString); + // var ex = new ArgumentException(message); + errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); + return false; + } + + isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); + if (!isUrlValid || url == null) + { + return false; + } + + } + + return true; + } + #endregion } } diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 5ce224c0f..ded1d008f 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -175,6 +175,25 @@ public static bool TryParseVersionOrVersionRange( #endregion #region Url methods + + // public static bool CreateValidUrl( + // string urlString, + + // out Uri urlResult, + // out ErrorRecord errorRecord + // ) + // { + // // create with url string as is + // bool isUrlValid = CreateUrl(urlString, out urlResult, out errorRecord); + + // // only if url creation fails, try to convert url from possibly relative path to absolute path and try again + // if (!isUrlValid && !CreateUrl(SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path, out urlResult, out errorRecord)) + // { + // return false; + // } + + // return true; + // } public static bool CreateUrl( string urlString, out Uri urlResult, diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 2907cfd6c..128fc46db 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -23,20 +23,14 @@ Describe "Test Register-PSResourceRepository" { Get-RemoveTestDirs($tmpDirPaths) } - It "should work on Windows and Linux" { - $resURL = "file:///tmp/testAnam/tmpDir1" - $tmpDirPath10 = "/tmp/testAnam/tmpDir1" - - $resURL | Should -Contain $tmpDirPath10 - } - It "register repository given Name, URL (bare minimum for NameParmaterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -PassThru $res.Name | Should -Be "testRepository" - Write-Host "$([regex]::Escape($tmpDir1Path))" - Write-Host $tmpDir1Path - Write-Host $res.URL - # $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" + # Write-Host "$([regex]::Escape($tmpDir1Path))" + # Write-Host $tmpDir1Path + # Write-Host $res.URL + # # $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" + Write-Host "uri path 1: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path # "$([regex]::Escape($tmpDir1Path))" | Should -Contain $res.URL @@ -50,6 +44,7 @@ Describe "Test Register-PSResourceRepository" { Write-Host "$([regex]::Escape($tmpDir1Path))" Write-Host $tmpDir1Path Write-Host $res.URL + Write-Host "uri path 2: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 50 @@ -58,6 +53,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL, Trusted, Priority (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -Priority 20 -PassThru $res.Name | Should -Be "testRepository" + Write-Host "uri path 3: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 20 @@ -98,17 +94,20 @@ Describe "Test Register-PSResourceRepository" { Register-PSResourceRepository -Repositories $arrayOfHashtables $res = Get-PSResourceRepository -Name "testRepository" - $res.URL | Should -Contain $tmpDir1Path + Write-Host "uri path 4.1: " $res.URL.AbsolutePath " should contain " $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Trusted | Should -Be False $res.Priority | Should -Be 50 $res2 = Get-PSResourceRepository -Name "testRepository2" - $res2.URL | Should -Contain $tmpDir2Path + Write-Host "uri path 4.2: " $res2.URL " should contain " $tmpDir2Path + $res2.URL.LocalPath | Should -Contain $tmpDir2Path $res2.Trusted | Should -Be True $res2.Priority | Should -Be 50 $res3 = Get-PSResourceRepository -Name "testRepository3" - $res3.URL | Should -Contain $tmpDir3Path + Write-Host "uri path 4.3: " $res3.URL " should contain " $tmpDir3Path + $res3.URL.LocalPath | Should -Contain $tmpDir3Path $res3.Trusted | Should -Be True $res3.Priority | Should -Be 20 } @@ -139,17 +138,20 @@ Describe "Test Register-PSResourceRepository" { $res1.Priority | Should -Be 50 $res2 = Get-PSResourceRepository -Name "testRepository" - $res2.URL | Should -Contain $tmpDir1Path + Write-Host "uri path 5.1: " $res2.URL.AbsolutePath " should contain " $tmpDir1Path + $res2.URL.LocalPath | Should -Contain $tmpDir1Path $res2.Trusted | Should -Be False $res2.Priority | Should -Be 50 $res3 = Get-PSResourceRepository -Name "testRepository2" - $res3.URL | Should -Contain $tmpDir2Path + Write-Host "uri path 5.2: " $res3.URL " should contain " $tmpDir2Path + $res3.URL.LocalPath | Should -Contain $tmpDir2Path $res3.Trusted | Should -Be True $res3.Priority | Should -Be 50 $res4 = Get-PSResourceRepository -Name "testRepository3" - $res4.URL | Should -Contain $tmpDir3Path + Write-Host "uri path 5.3: " $res4.URL.AbsolutePath " should contain " $tmpDir3Path + $res4.URL.LocalPath | Should -Contain $tmpDir3Path $res4.Trusted | Should -Be True $res4.Priority | Should -Be 20 } @@ -209,7 +211,7 @@ Describe "Test Register-PSResourceRepository" { $testCases2 = @{Type = "-Name is not specified"; IncorrectHashTable = @{URL = $tmpDir1Path}; ErrorId = "NullNameForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, @{Type = "-Name is PSGallery"; IncorrectHashTable = @{Name = "PSGallery"; URL = $tmpDir1Path}; ErrorId = "PSGalleryProvidedAsNameRepoPSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, @{Type = "-URL not specified"; IncorrectHashTable = @{Name = "testRepository"}; ErrorId = "NullURLForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-URL is not valid scheme"; IncorrectHashTable = @{Name = "testRepository"; URL="www.google.com"}; ErrorId = "InvalidUrlScheme,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"} + @{Type = "-URL is not valid scheme"; IncorrectHashTable = @{Name = "testRepository"; URL="www.google.com"}; ErrorId = "InvalidUrl,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"} It "not register incorrectly formatted Name type repo among correct ones when incorrect type is " -TestCases $testCases2 { param($Type, $IncorrectHashTable, $ErrorId) From 343eb551c3ce852b1e54183c348c752639d85582 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 12:30:38 -0400 Subject: [PATCH 05/16] set and register tests work on Linux and Windows now --- src/code/RegisterPSResourceRepository.cs | 139 +------------------- src/code/SetPSResourceRepository.cs | 103 +++++++++++---- test/RegisterPSResourceRepository.Tests.ps1 | 18 --- test/SetPSResourceRepository.Tests.ps1 | 18 +-- 4 files changed, 86 insertions(+), 192 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 596d67125..a8c0fd0d9 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -53,33 +53,6 @@ class RegisterPSResourceRepository : PSCmdlet [ValidateNotNullOrEmpty] public string URL { get; set; } - // /// - // /// Specifies the location of the repository to be registered. - // /// - // [Parameter(Mandatory = true, Position = 1, ParameterSetName = NameParameterSet)] - // [ValidateNotNullOrEmpty] - // public Uri URL { - // get - // { return _url; } - - // set - // { - // string urlString = SessionState.Path.GetResolvedPSPathFromPSPath(value.AbsoluteUri)[0].Path; - // // tryCreateResult = Uri.TryCreate(url, UriKind.Absolute, out _url); - - // if (!Uri.TryCreate(urlString, UriKind.Absolute, out Uri url)) - // { - // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", value); - // var ex = new ArgumentException(message); - // var moduleManifestNotFound = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); - // ThrowTerminatingError(moduleManifestNotFound); - // } - - // _url = url; - // } - // } - - /// /// When specified, registers PSGallery repository. /// @@ -167,27 +140,12 @@ protected override void ProcessRecord() { case NameParameterSet: string url = URL; - /*** trying to get it working */ bool isUrlValid = TryCreateURL(url, out _url, out ErrorRecord errorRecord); if (!isUrlValid) { ThrowTerminatingError(errorRecord); } - /** WORKS */ - // bool tryCreateResult = Utils.CreateUrl(url, out _url, out ErrorRecord errorRecord); - - // if (!tryCreateResult || _url == null) - // { - // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; - // bool tryWithResolvedPath = Utils.CreateUrl(url, out _url, out errorRecord); - // if (!tryWithResolvedPath || _url == null) - // { - // ThrowTerminatingError(errorRecord); - // } - // WriteVerbose(url); - // } - try { items.Add(NameParameterSetHelper(Name, _url, Priority, Trusted)); @@ -366,40 +324,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - // string url = repo["Url"].ToString(); - - // if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && - // !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && - // !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) - // { - // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; - // } - - // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); - - // if (!tryCreateResult || repoURL == null) - // { - // WriteError(errorRecord); - // return null; - // } - - - // string url = repo["Url"].ToString(); - // if (!repo["Url"].ToString().StartsWith(Uri.UriSchemeHttp) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeHttps) && !repo["Url"].ToString().StartsWith(Uri.UriSchemeFtp)) - // { - // url = SessionState.Path.GetResolvedPSPathFromPSPath(repo["Url"].ToString())[0].Path; - // } - - // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); - - // if (!tryCreateResult || repoURL == null) - // { - // WriteError(errorRecord); - // return null; - // } - string url = repo["Url"].ToString(); - /*** trying to get working */ bool isUrlValid = TryCreateURL(repo["Url"].ToString(), out Uri repoURL, out ErrorRecord errorRecord); if (!isUrlValid) { @@ -407,59 +332,6 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - - - /** WORKS */ - // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); - - // if (!tryCreateResult || repoURL == null) - // { - // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; - // bool tryWithResolvedPath = Utils.CreateUrl(url, out repoURL, out errorRecord); - // if (!tryWithResolvedPath || repoURL == null) - // { - // WriteError(errorRecord); - // } - // WriteVerbose(url); - // } - - - // bool tryCreateResult = Utils.CreateUrl(url, out Uri repoURL, out ErrorRecord errorRecord); - - // if (!tryCreateResult || repoURL == null) - // { - // url = SessionState.Path.GetResolvedPSPathFromPSPath(url)[0].Path; - // bool tryWithResolvedPath = Utils.CreateUrl(url, out repoURL, out errorRecord); - // if (!tryWithResolvedPath || repoURL == null) - // { - // WriteError(errorRecord); - // } - // WriteVerbose(url); - // } - - // bool tryCreateResult = Utils.CreateValidUrl(repo["Url"].ToString(), out Uri repoURL, out ErrorRecord errorRecord); - // // add condition repoURL == null (as a OR) - // if (!tryCreateResult) - // { - // WriteError(errorRecord); - // return null; - // } - // if (!tryCreateResult || repoURL == null) - // { - // WriteError(errorRecord); - // return null; - // } - - // if (!Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out Uri repoURL)) - // { - // WriteError(new ErrorRecord( - // new PSInvalidOperationException("Invalid url, unable to create"), - // "InvalidUrlScheme", - // ErrorCategory.InvalidArgument, - // this)); - // return null; - // } - try { WriteDebug(String.Format("(RepositoriesParameterSet): on repo: {0}. Registers Name based repository", repo["Name"])); @@ -490,15 +362,9 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRecord) { - // create with url string as is + // try to create with url string as is, so that absolute URIs are handled properly bool isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); - // // only if url creation fails, try to convert url from possibly relative path to absolute path and try again - // if (!isUrlValid && !Utils.CreateUrl(SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path, out url, out errorRecord)) - // { - // return false; - // } - // only if url creation fails, try to convert url from possibly relative path to absolute path and try again if (!isUrlValid && (!urlString.StartsWith(Uri.UriSchemeHttp) && !urlString.StartsWith(Uri.UriSchemeHttps) && @@ -511,8 +377,6 @@ private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRe } catch (Exception e) { - // var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", urlString); - // var ex = new ArgumentException(message); errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); return false; } @@ -522,7 +386,6 @@ private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRe { return false; } - } return true; diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index c3f161333..b01b1211b 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -1,3 +1,4 @@ +using System.Text; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -27,6 +28,7 @@ class SetPSResourceRepository : PSCmdlet private const string NameParameterSet = "NameParameterSet"; private const string RepositoriesParameterSet = "RepositoriesParameterSet"; private const int DefaultPriority = -1; + private Uri _url; #endregion #region Parameters @@ -45,25 +47,7 @@ class SetPSResourceRepository : PSCmdlet /// [Parameter(ParameterSetName = NameParameterSet)] [ValidateNotNullOrEmpty] - public Uri URL - { - get - { return _url; } - - set - { - if (!Uri.TryCreate(value, string.Empty, out Uri url)) - { - var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not a valid url: {0}", value); - var ex = new ArgumentException(message); - var urlErrorRecord = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); - ThrowTerminatingError(urlErrorRecord); - } - - _url = url; - } - } - private Uri _url; + public string URL { get; set; } /// /// Specifies a hashtable of repositories and is used to register multiple repositories at once. @@ -129,6 +113,17 @@ protected override void BeginProcessing() protected override void ProcessRecord() { + // string url = URL; + if (!String.IsNullOrEmpty(URL)) + { + bool isUrlValid = TryCreateURL(URL, out _url, out ErrorRecord errorRecord); + if (!isUrlValid) + { + ThrowTerminatingError(errorRecord); + } + } + + List items = new List(); switch(ParameterSetName) @@ -136,7 +131,7 @@ protected override void ProcessRecord() case NameParameterSet: try { - items.Add(UpdateRepositoryStoreHelper(Name, URL, Priority, Trusted)); + items.Add(UpdateRepositoryStoreHelper(Name, _url, Priority, Trusted)); } catch (Exception e) { @@ -243,17 +238,41 @@ private List RepositoriesParameterSetHelper() private PSRepositoryInfo RepoValidationHelper(Hashtable repo) { WriteDebug(String.Format("Parsing through repository: {0}", repo["Name"])); + Uri repoURL = null; - if (repo.ContainsKey("Url") && !Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out repoURL)) + if (repo.ContainsKey("Url")) { - WriteError(new ErrorRecord( - new PSInvalidOperationException("Invalid Url, unable to parse and create Uri"), - "InvalidUrl", - ErrorCategory.InvalidArgument, - this)); - return null; + if (String.IsNullOrEmpty(repo["Url"].ToString())) + { + WriteError(new ErrorRecord( + new PSInvalidOperationException("Repository url cannot be null if provided"), + "NullURLForRepositoriesParameterSetUpdate", + ErrorCategory.InvalidArgument, + this)); + return null; + } + + string url = repo["Url"].ToString(); + bool isUrlValid = TryCreateURL(repo["Url"].ToString(), out repoURL, out ErrorRecord errorRecord); + if (!isUrlValid) + { + WriteError(errorRecord); + return null; + } } + + + // if (repo.ContainsKey("Url") && !Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out repoURL)) + // { + // WriteError(new ErrorRecord( + // new PSInvalidOperationException("Invalid Url, unable to parse and create Uri"), + // "InvalidUrl", + // ErrorCategory.InvalidArgument, + // this)); + // return null; + // } + bool repoTrusted = false; isSet = false; if(repo.ContainsKey("Trusted")) @@ -279,6 +298,36 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } } + private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRecord) + { + // try to create with url string as is, so that absolute URIs are handled properly + bool isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); + + // only if url creation fails, try to convert url from possibly relative path to absolute path and try again + if (!isUrlValid && (!urlString.StartsWith(Uri.UriSchemeHttp) && + !urlString.StartsWith(Uri.UriSchemeHttps) && + !urlString.StartsWith(Uri.UriSchemeFtp))) + { + try + { + string resolvedUrlString = SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; + urlString = resolvedUrlString; + } + catch (Exception e) + { + errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); + return false; + } + + isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); + if (!isUrlValid || url == null) + { + return false; + } + } + + return true; + } #endregion } } diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 128fc46db..6d76df5df 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -26,14 +26,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL (bare minimum for NameParmaterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -PassThru $res.Name | Should -Be "testRepository" - # Write-Host "$([regex]::Escape($tmpDir1Path))" - # Write-Host $tmpDir1Path - # Write-Host $res.URL - # # $res.URL | Should -Contain "$([regex]::Escape($tmpDir1Path))" - Write-Host "uri path 1: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path - # "$([regex]::Escape($tmpDir1Path))" | Should -Contain $res.URL - $res.Trusted | Should -Be False $res.Priority | Should -Be 50 } @@ -41,10 +34,6 @@ Describe "Test Register-PSResourceRepository" { It "register repository with Name, URL, Trusted (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -PassThru $res.Name | Should -Be "testRepository" - Write-Host "$([regex]::Escape($tmpDir1Path))" - Write-Host $tmpDir1Path - Write-Host $res.URL - Write-Host "uri path 2: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 50 @@ -53,7 +42,6 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL, Trusted, Priority (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -Priority 20 -PassThru $res.Name | Should -Be "testRepository" - Write-Host "uri path 3: " $res.URL " should contain " $tmpDir1Path $res.URL | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 20 @@ -94,19 +82,16 @@ Describe "Test Register-PSResourceRepository" { Register-PSResourceRepository -Repositories $arrayOfHashtables $res = Get-PSResourceRepository -Name "testRepository" - Write-Host "uri path 4.1: " $res.URL.AbsolutePath " should contain " $tmpDir1Path $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Trusted | Should -Be False $res.Priority | Should -Be 50 $res2 = Get-PSResourceRepository -Name "testRepository2" - Write-Host "uri path 4.2: " $res2.URL " should contain " $tmpDir2Path $res2.URL.LocalPath | Should -Contain $tmpDir2Path $res2.Trusted | Should -Be True $res2.Priority | Should -Be 50 $res3 = Get-PSResourceRepository -Name "testRepository3" - Write-Host "uri path 4.3: " $res3.URL " should contain " $tmpDir3Path $res3.URL.LocalPath | Should -Contain $tmpDir3Path $res3.Trusted | Should -Be True $res3.Priority | Should -Be 20 @@ -138,19 +123,16 @@ Describe "Test Register-PSResourceRepository" { $res1.Priority | Should -Be 50 $res2 = Get-PSResourceRepository -Name "testRepository" - Write-Host "uri path 5.1: " $res2.URL.AbsolutePath " should contain " $tmpDir1Path $res2.URL.LocalPath | Should -Contain $tmpDir1Path $res2.Trusted | Should -Be False $res2.Priority | Should -Be 50 $res3 = Get-PSResourceRepository -Name "testRepository2" - Write-Host "uri path 5.2: " $res3.URL " should contain " $tmpDir2Path $res3.URL.LocalPath | Should -Contain $tmpDir2Path $res3.Trusted | Should -Be True $res3.Priority | Should -Be 50 $res4 = Get-PSResourceRepository -Name "testRepository3" - Write-Host "uri path 5.3: " $res4.URL.AbsolutePath " should contain " $tmpDir3Path $res4.URL.LocalPath | Should -Contain $tmpDir3Path $res4.Trusted | Should -Be True $res4.Priority | Should -Be 20 diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index 24cb5dfc3..f6357ae8d 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -28,7 +28,7 @@ Describe "Test Register-PSResourceRepository" { Set-PSResourceRepository -Name "testRepository" -URL $tmpDir2Path $res = Get-PSResourceRepository -Name "testRepository" $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir2Path + $res.URL.LocalPath | Should -Contain $tmpDir2Path $res.Priority | Should -Be 50 $res.Trusted | Should -Be False } @@ -38,7 +38,7 @@ Describe "Test Register-PSResourceRepository" { Set-PSResourceRepository -Name "testRepository" -Priority 25 $res = Get-PSResourceRepository -Name "testRepository" $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Priority | Should -Be 25 $res.Trusted | Should -Be False } @@ -48,7 +48,7 @@ Describe "Test Register-PSResourceRepository" { Set-PSResourceRepository -Name "testRepository" -Trusted $res = Get-PSResourceRepository -Name "testRepository" $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Priority | Should -Be 50 $res.Trusted | Should -Be True } @@ -59,8 +59,8 @@ Describe "Test Register-PSResourceRepository" { } $testCases = @{Type = "contains *"; Name = "test*Repository"; ErrorId = "ErrorInNameParameterSet"}, - @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorInNameParameterSet"}, - @{Type = "is null"; Name = $null; ErrorId = "ParameterArgumentValidationError"} + @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorInNameParameterSet"}, + @{Type = "is null"; Name = $null; ErrorId = "ParameterArgumentValidationError"} It "not set repository and throw error given Name (NameParameterSet)" -TestCases $testCases { param($Type, $Name) @@ -88,7 +88,7 @@ Describe "Test Register-PSResourceRepository" { $err[0].FullyQualifiedErrorId | Should -BeExactly "$ErrorId,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name "testRepository" - $res.URL | Should -Contain $tmpDir3Path + $res.URL.LocalPath | Should -Contain $tmpDir3Path $res.Trusted | Should -Be False $res2 = Get-PSResourceRepository -Name "testRepository2" @@ -110,13 +110,13 @@ Describe "Test Register-PSResourceRepository" { Set-PSResourceRepository -Repositories $arrayOfHashtables $res = Get-PSResourceRepository -Name "testRepository1" $res.Name | Should -Be "testRepository1" - $res.URL | Should -Contain $tmpDir2Path + $res.URL.LocalPath | Should -Contain $tmpDir2Path $res.Priority | Should -Be 50 $res.Trusted | Should -Be False $res2 = Get-PSResourceRepository -Name "testRepository2" $res2.Name | Should -Be "testRepository2" - $res2.URL | Should -Contain $tmpDir2Path + $res2.URL.LocalPath | Should -Contain $tmpDir2Path $res2.Priority | Should -Be 25 $res2.Trusted | Should -Be False @@ -148,7 +148,7 @@ Describe "Test Register-PSResourceRepository" { $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingIndividualRepoFromRepositories,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Priority | Should -Be 25 $res.Trusted | Should -Be False } From f24e9618c4ff8962114227a90f90b4ccb688cd5b Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 12:42:34 -0400 Subject: [PATCH 06/16] revert accidental changes --- .vscode/launch.json | 2 +- nuget.config | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index ab4404aaf..036014deb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -27,7 +27,7 @@ "name": ".NET Core Attach", "type": "coreclr", "request": "attach", - "processId": "195" + "processId": "${command:pickProcess}" } ] } \ No newline at end of file diff --git a/nuget.config b/nuget.config index 2029fc205..654858614 100644 --- a/nuget.config +++ b/nuget.config @@ -1,9 +1,8 @@ - + - From 325dd2104b9962861ec48977f70ae4f6ac9f1fbe Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 12:44:39 -0400 Subject: [PATCH 07/16] remove accidental change to InstallHelper --- src/code/InstallHelper.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 648d77462..1679c06fa 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -347,10 +347,7 @@ private List InstallPackage(IEnumerable pkgsToInstall, s } catch (Exception e) { - var message = string.Format("Error attempting download: '{0}'", e.Message); - var ex = new ArgumentException(message); - var installException = new ErrorRecord(ex, "InstallDownloadException", ErrorCategory.InvalidResult , null); - _cmdletPassedIn.WriteError(installException); + _cmdletPassedIn.WriteDebug(string.Format("Error attempting download: '{0}'", e.Message)); } finally { From afcfd66b65479cdf165db50504e6834c4658abb2 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 12:47:20 -0400 Subject: [PATCH 08/16] remove uneccessary variable --- src/code/RegisterPSResourceRepository.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index a8c0fd0d9..864efcaa1 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -139,8 +139,7 @@ protected override void ProcessRecord() switch (ParameterSetName) { case NameParameterSet: - string url = URL; - bool isUrlValid = TryCreateURL(url, out _url, out ErrorRecord errorRecord); + bool isUrlValid = TryCreateURL(URL, out _url, out ErrorRecord errorRecord); if (!isUrlValid) { ThrowTerminatingError(errorRecord); From 1d09ed6e8e51197a9af6be795e573c8354a8fef4 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 12:50:52 -0400 Subject: [PATCH 09/16] remove comments --- src/code/SetPSResourceRepository.cs | 14 +------------- src/code/Utils.cs | 18 ------------------ 2 files changed, 1 insertion(+), 31 deletions(-) diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index b01b1211b..5ae782b9b 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -1,4 +1,3 @@ -using System.Text; // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. @@ -8,6 +7,7 @@ using Dbg = System.Diagnostics.Debug; using System.Globalization; using System.Management.Automation; +using System.Text; using Microsoft.PowerShell.PowerShellGet.UtilClasses; namespace Microsoft.PowerShell.PowerShellGet.Cmdlets @@ -261,18 +261,6 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } } - - - // if (repo.ContainsKey("Url") && !Uri.TryCreate(repo["URL"].ToString(), UriKind.Absolute, out repoURL)) - // { - // WriteError(new ErrorRecord( - // new PSInvalidOperationException("Invalid Url, unable to parse and create Uri"), - // "InvalidUrl", - // ErrorCategory.InvalidArgument, - // this)); - // return null; - // } - bool repoTrusted = false; isSet = false; if(repo.ContainsKey("Trusted")) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index ded1d008f..af75a2f66 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -176,24 +176,6 @@ public static bool TryParseVersionOrVersionRange( #region Url methods - // public static bool CreateValidUrl( - // string urlString, - - // out Uri urlResult, - // out ErrorRecord errorRecord - // ) - // { - // // create with url string as is - // bool isUrlValid = CreateUrl(urlString, out urlResult, out errorRecord); - - // // only if url creation fails, try to convert url from possibly relative path to absolute path and try again - // if (!isUrlValid && !CreateUrl(SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path, out urlResult, out errorRecord)) - // { - // return false; - // } - - // return true; - // } public static bool CreateUrl( string urlString, out Uri urlResult, From 96ace2343f4e7b2d14ffff7391b06820e4b6cc3e Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 13:55:41 -0400 Subject: [PATCH 10/16] push some todo comments I need to resolve --- src/code/RegisterPSResourceRepository.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 864efcaa1..c4f847990 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -34,6 +34,7 @@ class RegisterPSResourceRepository : PSCmdlet private const string NameParameterSet = "NameParameterSet"; private const string PSGalleryParameterSet = "PSGalleryParameterSet"; private const string RepositoriesParameterSet = "RepositoriesParameterSet"; + private Uri _url; #endregion @@ -106,7 +107,6 @@ class RegisterPSResourceRepository : PSCmdlet #endregion #region Methods - private Uri _url; protected override void BeginProcessing() { @@ -371,6 +371,8 @@ private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRe { try { + // /tmp/Users/annavied -> Uri.UriSchemeFile ? (Todo: retry and see if condition above checks for Uri.Filescheme if we can detect) + // www.google.com -> C:/Users/annavied/www.google.com string resolvedUrlString = SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; urlString = resolvedUrlString; } @@ -387,7 +389,7 @@ private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRe } } - return true; + return isUrlValid; } #endregion From f1efe5a872604b7a4ab4ce01970738a9ca9617f2 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 18:10:29 -0400 Subject: [PATCH 11/16] refactor and clean up --- src/code/RegisterPSResourceRepository.cs | 39 ++---------------- src/code/SetPSResourceRepository.cs | 36 +---------------- src/code/Utils.cs | 44 +++++++++++++-------- test/RegisterPSResourceRepository.Tests.ps1 | 6 +-- 4 files changed, 35 insertions(+), 90 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index c4f847990..0b482284d 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -139,7 +139,7 @@ protected override void ProcessRecord() switch (ParameterSetName) { case NameParameterSet: - bool isUrlValid = TryCreateURL(URL, out _url, out ErrorRecord errorRecord); + bool isUrlValid = Utils.TryCreateValidUrl(URL, this, out _url, out ErrorRecord errorRecord); if (!isUrlValid) { ThrowTerminatingError(errorRecord); @@ -324,7 +324,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } string url = repo["Url"].ToString(); - bool isUrlValid = TryCreateURL(repo["Url"].ToString(), out Uri repoURL, out ErrorRecord errorRecord); + bool isUrlValid = Utils.TryCreateValidUrl(url, this, out Uri repoURL, out ErrorRecord errorRecord); if (!isUrlValid) { WriteError(errorRecord); @@ -359,39 +359,6 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } } - private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRecord) - { - // try to create with url string as is, so that absolute URIs are handled properly - bool isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); - - // only if url creation fails, try to convert url from possibly relative path to absolute path and try again - if (!isUrlValid && (!urlString.StartsWith(Uri.UriSchemeHttp) && - !urlString.StartsWith(Uri.UriSchemeHttps) && - !urlString.StartsWith(Uri.UriSchemeFtp))) - { - try - { - // /tmp/Users/annavied -> Uri.UriSchemeFile ? (Todo: retry and see if condition above checks for Uri.Filescheme if we can detect) - // www.google.com -> C:/Users/annavied/www.google.com - string resolvedUrlString = SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; - urlString = resolvedUrlString; - } - catch (Exception e) - { - errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); - return false; - } - - isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); - if (!isUrlValid || url == null) - { - return false; - } - } - - return isUrlValid; - } - - #endregion + #endregion } } diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 5ae782b9b..ee41d4a54 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -113,17 +113,15 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - // string url = URL; if (!String.IsNullOrEmpty(URL)) { - bool isUrlValid = TryCreateURL(URL, out _url, out ErrorRecord errorRecord); + bool isUrlValid = Utils.TryCreateValidUrl(URL, this, out _url, out ErrorRecord errorRecord); if (!isUrlValid) { ThrowTerminatingError(errorRecord); } } - List items = new List(); switch(ParameterSetName) @@ -253,7 +251,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } string url = repo["Url"].ToString(); - bool isUrlValid = TryCreateURL(repo["Url"].ToString(), out repoURL, out ErrorRecord errorRecord); + bool isUrlValid = Utils.TryCreateValidUrl(url, this, out repoURL, out ErrorRecord errorRecord); if (!isUrlValid) { WriteError(errorRecord); @@ -286,36 +284,6 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) } } - private bool TryCreateURL(string urlString, out Uri url, out ErrorRecord errorRecord) - { - // try to create with url string as is, so that absolute URIs are handled properly - bool isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); - - // only if url creation fails, try to convert url from possibly relative path to absolute path and try again - if (!isUrlValid && (!urlString.StartsWith(Uri.UriSchemeHttp) && - !urlString.StartsWith(Uri.UriSchemeHttps) && - !urlString.StartsWith(Uri.UriSchemeFtp))) - { - try - { - string resolvedUrlString = SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; - urlString = resolvedUrlString; - } - catch (Exception e) - { - errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); - return false; - } - - isUrlValid = Utils.CreateUrl(urlString, out url, out errorRecord); - if (!isUrlValid || url == null) - { - return false; - } - } - - return true; - } #endregion } } diff --git a/src/code/Utils.cs b/src/code/Utils.cs index af75a2f66..a69dd590b 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -176,41 +176,51 @@ public static bool TryParseVersionOrVersionRange( #region Url methods - public static bool CreateUrl( + public static bool TryCreateValidUrl( string urlString, + PSCmdlet cmdletPassedIn, out Uri urlResult, out ErrorRecord errorRecord ) { - // string url = SessionState.Path.GetResolvedPSPathFromPSPath(URL)[0].Path; - bool tryCreateResult = false; - try - { - tryCreateResult = Uri.TryCreate(urlString, UriKind.Absolute, out urlResult); - } - catch (Exception e) + errorRecord = null; + + if (!urlString.StartsWith(Uri.UriSchemeHttps) && + !urlString.StartsWith(Uri.UriSchemeHttp) && + !urlString.StartsWith(Uri.UriSchemeFtp)) { - var message = string.Format("Uri.TryCreate on provided Url string: " + urlString + " threw error: " + e.Message); - var ex = new ArgumentException(message); - errorRecord = new ErrorRecord(ex, "TryCreateFails", ErrorCategory.InvalidArgument, null); - urlResult = null; - return false; + // url string could be of type (potentially) UriSchemeFile or invalid type + // can't check for UriSchemeFile because relative paths don't qualify as UriSchemeFile + try + { + // this is needed for a relative path urlstring. Does not throw error for an absolute path + string resolvedUrlString = cmdletPassedIn.SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; + urlString = resolvedUrlString; + + } + catch (Exception e) + { + // this should only be reached if the url string is invalid + // i.e www.google.com + // error message will look like: Cannot find path 'C:\Users\annavied\Documents\PowerShellGet\www.google.com' because it does not exist. + errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); + urlResult = null; + return false; + } } + bool tryCreateResult = Uri.TryCreate(urlString, UriKind.Absolute, out urlResult); if (!tryCreateResult) { var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0}", urlString); var ex = new ArgumentException(message); errorRecord = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); urlResult = null; - return false; } - // otherwise Url (urlResult) was successfully created in Uri.TryCreate() call - errorRecord = null; return tryCreateResult; - } + #endregion #region Path methods diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 6d76df5df..8fb7fdcfe 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -26,7 +26,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL (bare minimum for NameParmaterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Trusted | Should -Be False $res.Priority | Should -Be 50 } @@ -34,7 +34,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository with Name, URL, Trusted (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 50 } @@ -42,7 +42,7 @@ Describe "Test Register-PSResourceRepository" { It "register repository given Name, URL, Trusted, Priority (NameParameterSet)" { $res = Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path -Trusted -Priority 20 -PassThru $res.Name | Should -Be "testRepository" - $res.URL | Should -Contain $tmpDir1Path + $res.URL.LocalPath | Should -Contain $tmpDir1Path $res.Trusted | Should -Be True $res.Priority | Should -Be 20 } From 6281802af81e06f09bd6059d01fb0f5b4464c696 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 18:12:50 -0400 Subject: [PATCH 12/16] remove unneccessary directive --- src/code/SetPSResourceRepository.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index ee41d4a54..258331e0f 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -7,7 +7,6 @@ using Dbg = System.Diagnostics.Debug; using System.Globalization; using System.Management.Automation; -using System.Text; using Microsoft.PowerShell.PowerShellGet.UtilClasses; namespace Microsoft.PowerShell.PowerShellGet.Cmdlets From de78219680db180ad44b5f48af85270adc9a3bf1 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 19:41:52 -0400 Subject: [PATCH 13/16] resolve PR styling feedback --- src/code/RegisterPSResourceRepository.cs | 13 ++++++++----- src/code/SetPSResourceRepository.cs | 9 +++++---- src/code/Utils.cs | 3 +-- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 0b482284d..d019071c6 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -139,8 +139,10 @@ protected override void ProcessRecord() switch (ParameterSetName) { case NameParameterSet: - bool isUrlValid = Utils.TryCreateValidUrl(URL, this, out _url, out ErrorRecord errorRecord); - if (!isUrlValid) + if (!Utils.TryCreateValidUrl(urlString: URL, + cmdletPassedIn: this, + urlResult: out _url, + errorRecord: out ErrorRecord errorRecord)) { ThrowTerminatingError(errorRecord); } @@ -323,9 +325,10 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - string url = repo["Url"].ToString(); - bool isUrlValid = Utils.TryCreateValidUrl(url, this, out Uri repoURL, out ErrorRecord errorRecord); - if (!isUrlValid) + if (!Utils.TryCreateValidUrl(urlString: repo["Url"].ToString(), + cmdletPassedIn: this, + urlResult: out Uri repoURL, + errorRecord: out ErrorRecord errorRecord)) { WriteError(errorRecord); return null; diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 258331e0f..5f674f02f 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -112,7 +112,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - if (!String.IsNullOrEmpty(URL)) + if (MyInvocation.BoundParameters.ContainsKey(nameof(URL))) { bool isUrlValid = Utils.TryCreateValidUrl(URL, this, out _url, out ErrorRecord errorRecord); if (!isUrlValid) @@ -249,9 +249,10 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - string url = repo["Url"].ToString(); - bool isUrlValid = Utils.TryCreateValidUrl(url, this, out repoURL, out ErrorRecord errorRecord); - if (!isUrlValid) + if (!Utils.TryCreateValidUrl(urlString: repo["Url"].ToString(), + cmdletPassedIn: this, + urlResult: out repoURL, + errorRecord: out ErrorRecord errorRecord)) { WriteError(errorRecord); return null; diff --git a/src/code/Utils.cs b/src/code/Utils.cs index a69dd590b..89f038e07 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -194,8 +194,7 @@ out ErrorRecord errorRecord try { // this is needed for a relative path urlstring. Does not throw error for an absolute path - string resolvedUrlString = cmdletPassedIn.SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; - urlString = resolvedUrlString; + urlString = cmdletPassedIn.SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; } catch (Exception e) From 8363f60abf52c9c25733c80319d68e5f0f3974d9 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Tue, 27 Jul 2021 19:54:42 -0400 Subject: [PATCH 14/16] change error message for invalid url to be more insightful for user --- src/code/Utils.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 89f038e07..492d07025 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -197,12 +197,13 @@ out ErrorRecord errorRecord urlString = cmdletPassedIn.SessionState.Path.GetResolvedPSPathFromPSPath(urlString)[0].Path; } - catch (Exception e) + catch (Exception) { // this should only be reached if the url string is invalid // i.e www.google.com - // error message will look like: Cannot find path 'C:\Users\annavied\Documents\PowerShellGet\www.google.com' because it does not exist. - errorRecord = new ErrorRecord(e, "InvalidUrl", ErrorCategory.InvalidArgument, null); + var message = string.Format(CultureInfo.InvariantCulture, "The URL provided is not valid: {0} and must be of Uri Scheme: HTTP, HTTPS, FTP or File", urlString); + var ex = new ArgumentException(message); + errorRecord = new ErrorRecord(ex, "InvalidUrl", ErrorCategory.InvalidArgument, null); urlResult = null; return false; } From 761c82689ba806e62ea13563f7aec2b8e56c26ee Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Wed, 28 Jul 2021 12:45:37 -0400 Subject: [PATCH 15/16] add tests with relative path --- test/RegisterPSResourceRepository.Tests.ps1 | 12 ++++++++++++ test/SetPSResourceRepository.Tests.ps1 | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 8fb7fdcfe..0640ac7bb 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -13,6 +13,8 @@ Describe "Test Register-PSResourceRepository" { $tmpDir3Path = Join-Path -Path $TestDrive -ChildPath "tmpDir3" $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-NewTestDirs($tmpDirPaths) + + $relativeCurrentPath = Pop-Location -PassThru } AfterEach { Get-RevertPSResourceRepositoryFile @@ -21,6 +23,7 @@ Describe "Test Register-PSResourceRepository" { $tmpDir3Path = Join-Path -Path $TestDrive -ChildPath "tmpDir3" $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-RemoveTestDirs($tmpDirPaths) + Pop-Location } It "register repository given Name, URL (bare minimum for NameParmaterSet)" { @@ -218,4 +221,13 @@ Describe "Test Register-PSResourceRepository" { $res3.Name | Should -Be "PSGallery" $res3.Priority | Should -Be 30 } + + It "should register repository with relative location provided as URL" { + Register-PSResourceRepository -Name "testRepository" -URL "./" + $res = Get-PSResourceRepository -Name "testRepository" + $res.Name | Should -Be "testRepository" + $res.URL.LocalPath | Should -Contain $relativeCurrentPath + $res.Trusted | Should -Be False + $res.Priority | Should -Be 50 + } } diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index f6357ae8d..2358c3079 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -13,6 +13,8 @@ Describe "Test Register-PSResourceRepository" { $tmpDir3Path = Join-Path -Path $TestDrive -ChildPath "tmpDir3" $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-NewTestDirs($tmpDirPaths) + + $relativeCurrentPath = Pop-Location -PassThru } AfterEach { Get-RevertPSResourceRepositoryFile @@ -152,4 +154,14 @@ Describe "Test Register-PSResourceRepository" { $res.Priority | Should -Be 25 $res.Trusted | Should -Be False } + + It "should set repository with relative URL provided" { + Register-PSResourceRepository -Name "testRepository" -URL $tmpDir1Path + Set-PSResourceRepository -Name "testRepository" -URL $relativeCurrentPath + $res = Get-PSResourceRepository -Name "testRepository" + $res.Name | Should -Be "testRepository" + $res.URL.LocalPath | Should -Contain $relativeCurrentPath + $res.Trusted | Should -Be False + $res.Priority | Should -Be 50 + } } From 9223c74b65238b1aab11313b1114eed4536db246 Mon Sep 17 00:00:00 2001 From: Anam Navied Date: Wed, 28 Jul 2021 15:34:06 -0400 Subject: [PATCH 16/16] use Get-Location to get current location --- test/RegisterPSResourceRepository.Tests.ps1 | 4 ++-- test/SetPSResourceRepository.Tests.ps1 | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index 0640ac7bb..fd4204774 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -14,7 +14,7 @@ Describe "Test Register-PSResourceRepository" { $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-NewTestDirs($tmpDirPaths) - $relativeCurrentPath = Pop-Location -PassThru + $relativeCurrentPath = Get-Location } AfterEach { Get-RevertPSResourceRepositoryFile @@ -23,7 +23,6 @@ Describe "Test Register-PSResourceRepository" { $tmpDir3Path = Join-Path -Path $TestDrive -ChildPath "tmpDir3" $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-RemoveTestDirs($tmpDirPaths) - Pop-Location } It "register repository given Name, URL (bare minimum for NameParmaterSet)" { @@ -225,6 +224,7 @@ Describe "Test Register-PSResourceRepository" { It "should register repository with relative location provided as URL" { Register-PSResourceRepository -Name "testRepository" -URL "./" $res = Get-PSResourceRepository -Name "testRepository" + $res.Name | Should -Be "testRepository" $res.URL.LocalPath | Should -Contain $relativeCurrentPath $res.Trusted | Should -Be False diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index 2358c3079..c302c3d79 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -3,7 +3,7 @@ Import-Module "$psscriptroot\PSGetTestUtils.psm1" -Force -Describe "Test Register-PSResourceRepository" { +Describe "Test Set-PSResourceRepository" { BeforeEach { $PSGalleryName = Get-PSGalleryName $PSGalleryURL = Get-PSGalleryLocation @@ -14,7 +14,7 @@ Describe "Test Register-PSResourceRepository" { $tmpDirPaths = @($tmpDir1Path, $tmpDir2Path, $tmpDir3Path) Get-NewTestDirs($tmpDirPaths) - $relativeCurrentPath = Pop-Location -PassThru + $relativeCurrentPath = Get-Location } AfterEach { Get-RevertPSResourceRepositoryFile