diff --git a/.config/tsaoptions.json b/.config/tsaoptions.json index 692eaec1f..6c5c94847 100644 --- a/.config/tsaoptions.json +++ b/.config/tsaoptions.json @@ -1,10 +1,10 @@ { - "instanceUrl": "https://msazure.visualstudio.com", - "projectName": "One", - "areaPath": "One\\MGMT\\Compute\\Powershell\\Powershell\\PowerShell Core", - "notificationAliases": [ - "adityap@microsoft.com", - "americks@microsoft.com", - "annavied@microsoft.com" - ] + "instanceUrl": "https://msazure.visualstudio.com", + "projectName": "One", + "areaPath": "One\\MGMT\\Compute\\Powershell\\Powershell\\PowerShell Core", + "notificationAliases": [ + "adityap@microsoft.com", + "americks@microsoft.com", + "annavied@microsoft.com" + ] } diff --git a/.editorconfig b/.editorconfig index 686da5c9f..d77f8ad1f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,14 @@ +# Copied from PowerShell/PowerShell 2025-06-28 +# https://github.com/PowerShell/PowerShell/blob/master/.editorconfig +# +# # EditorConfig is awesome: https://EditorConfig.org # .NET coding convention settings for EditorConfig # https://learn.microsoft.com/visualstudio/ide/editorconfig-code-style-settings-reference # -# This file was taken from PowerShell/PowerShell 2024-07-13 -# https://github.com/PowerShell/PowerShell/blob/master/.editorconfig +# This file comes from dotnet repositories: +# https://github.com/dotnet/runtime/blob/master/.editorconfig +# https://github.com/dotnet/roslyn/blob/master/.editorconfig # Top-most EditorConfig file root = true @@ -102,6 +107,8 @@ dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case # Suggest more modern language features when available dotnet_style_object_initializer = true:suggestion dotnet_style_collection_initializer = true:suggestion +# Background Info: https://github.com/dotnet/runtime/pull/100250 +dotnet_style_prefer_collection_expression = when_types_exactly_match dotnet_style_coalesce_expression = true:suggestion dotnet_style_null_propagation = true:suggestion dotnet_style_explicit_tuple_names = true:suggestion @@ -116,6 +123,13 @@ csharp_prefer_simple_default_expression = true:suggestion dotnet_code_quality_unused_parameters = non_public:suggestion +# Dotnet diagnostic settings: +[*.cs] + +# CA1859: Use concrete types when possible for improved performance +# https://learn.microsoft.com/en-gb/dotnet/fundamentals/code-analysis/quality-rules/ca1859 +dotnet_diagnostic.CA1859.severity = suggestion + # CSharp code style settings: [*.cs] diff --git a/.gitignore b/.gitignore index e035e30c7..a0760ee7e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,5 @@ out test/**/obj test/**/bin .vs -.vscode src/code/.vs -test/testFiles/testScripts/test.ps1 \ No newline at end of file +test/testFiles/testScripts/test.ps1 diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 000000000..cf889c7a2 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,22 @@ +{ + "default": true, + "MD004": false, + "MD007": { + "indent": 4 + }, + "MD013": { + "line_length": 240 + }, + "MD026": { + "punctuation": ".,;:!" + }, + "MD029": { + "style": "one" + }, + "MD033": false, + "MD034": false, + "MD038": false, + "MD042": false, + "MD024": false, + "no-hard-tabs": true +} diff --git a/.markdownlintignore b/.markdownlintignore new file mode 100644 index 000000000..1d3c5b1ac --- /dev/null +++ b/.markdownlintignore @@ -0,0 +1 @@ +.github/SECURITY.md diff --git a/.vscode/extensions.json b/.vscode/extensions.json index d2f30467c..31fe68319 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,14 +1,11 @@ { - // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. - // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp - // List of extensions which should be recommended for users of this workspace. - "recommendations": [ - "EditorConfig.EditorConfig", + "recommendations": [ + "DavidAnson.vscode-markdownlint", + "EditorConfig.EditorConfig", "ms-dotnettools.csdevkit", - "ms-dotnettools.csharp", - "ms-vscode.powershell", - "patcx.vscode-nuget-gallery" - ], - // List of extensions recommended by VS Code that should not be recommended for users of this workspace. - "unwantedRecommendations": [] + "ms-dotnettools.csharp", + "ms-vscode.powershell", + "patcx.vscode-nuget-gallery" + ], + "unwantedRecommendations": [] } diff --git a/.vscode/launch.json b/.vscode/launch.json index 82c604272..56432e87d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,33 +1,33 @@ { - "version": "0.2.0", - "configurations": [ - { - "name": "Debug PSModule", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "publish", - "program": "pwsh", - "args": [ - "-noprofile", - "-noexit", - "-c", - "Import-Module ${workspaceFolder}/out/PowerShellGet.dll -Verbose" - ], - "cwd": "${workspaceFolder}", - "console": "externalTerminal", - "stopAtEntry": false, - "logging": { - "logging.diagnosticsLog.protocolMessages": false, - "moduleLoad": false, - "exceptions": false, - "browserStdOut": false - } - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ] + "version": "0.2.0", + "configurations": [ + { + "name": "Debug PSModule", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "publish", + "program": "pwsh", + "args": [ + "-noprofile", + "-noexit", + "-c", + "Import-Module ${workspaceFolder}/out/PowerShellGet.dll -Verbose" + ], + "cwd": "${workspaceFolder}", + "console": "externalTerminal", + "stopAtEntry": false, + "logging": { + "logging.diagnosticsLog.protocolMessages": false, + "moduleLoad": false, + "exceptions": false, + "browserStdOut": false + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 1dea6f957..2df8cf3f7 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,15 @@ { - "csharp.semanticHighlighting.enabled": true, - "dotnet.automaticallyCreateSolutionInWorkspace": false, - "omnisharp.enableEditorConfigSupport": true, - "omnisharp.enableRoslynAnalyzers": true + "[powershell]": { + "files.trimTrailingWhitespace": true + }, + "csharp.semanticHighlighting.enabled": true, + "editor.insertSpaces": true, + "dotnet.automaticallyCreateSolutionInWorkspace": false, + "omnisharp.enableEditorConfigSupport": true, + "omnisharp.enableRoslynAnalyzers": true, + "powershell.codeFormatting.preset": "OTBS", + "powershell.codeFormatting.whitespaceAfterSeparator": true, + "powershell.codeFormatting.whitespaceAroundOperator": true, + "powershell.codeFormatting.whitespaceBeforeOpenBrace": true, + "powershell.codeFormatting.whitespaceBeforeOpenParen": true } diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 600e5eee1..a217ba5d0 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,48 +1,48 @@ { - // See https://go.microsoft.com/fwlink/?LinkId=733558 - // for the documentation about the tasks.json format - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "command": "dotnet", - "type": "shell", - "args": [ - "build", - "src/code", - // Ask dotnet build to generate full paths for file names. - "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel - "/consoleloggerparameters:NoSummary" - ], - "group": "build", - "presentation": { - "revealProblems": "onProblem", - "clear": true, - }, - "problemMatcher": "$msCompile" - }, - { - "label": "publish", - "command": "dotnet", - "type": "shell", - "args": [ - "publish", - "src/code", - "-o", - "out", - "--framework", - "net472", - // Ask dotnet build to generate full paths for file names. - "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel - "/consoleloggerparameters:NoSummary" - ], - "group": "build", - "presentation": { - "reveal": "silent" - }, - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "shell", + "args": [ + "build", + "src/code", + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary" + ], + "group": "build", + "presentation": { + "revealProblems": "onProblem", + "clear": true, + }, + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "shell", + "args": [ + "publish", + "src/code", + "-o", + "out", + "--framework", + "net472", + // Ask dotnet build to generate full paths for file names. + "/property:GenerateFullPaths=true", + // Do not generate summary otherwise it leads to duplicate errors in Problems panel + "/consoleloggerparameters:NoSummary" + ], + "group": "build", + "presentation": { + "reveal": "silent" + }, + "problemMatcher": "$msCompile" + } + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 08dacccbd..0c3a1d2c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1 @@ -The change logs have been split by version and moved to [CHANGELOG](./CHANGELOG). \ No newline at end of file +The change logs have been split by version and moved to [CHANGELOG](./CHANGELOG). diff --git a/CHANGELOG/1.0.md b/CHANGELOG/1.0.md index 20348dea3..ac1f7734f 100644 --- a/CHANGELOG/1.0.md +++ b/CHANGELOG/1.0.md @@ -330,19 +330,19 @@ - Support searching for all packages from a repository (i.e `Find-PSResource -Name '*'`). Note, wildcard search is not supported for AzureDevOps feed repositories and will write an error message accordingly. - Packages found are now unique by Name,Version,Repository. - Support searching for and returning packages found across multiple repositories when using wildcard with Repository parameter (i.e `Find-PSResource -Name 'PackageExistingInMultipleRepos' -Repository '*'` will perform an exhaustive search). - - PSResourceInfo objects can be piped into: `Install-PSResource`, `Uninstall-PSResource`, `Save-PSResource`. PSRepositoryInfo objects can be piped into: `Unregister-PSResourceRepository` + - PSResourceInfo objects can be piped into: `Install-PSResource`, `Uninstall-PSResource`, `Save-PSResource`. PSRepositoryInfo objects can be piped into: `Unregister-PSResourceRepository` - For more consistent pipeline support, the following cmdlets have pipeline support for the listed parameter(s): - - `Find-PSResource` (Name param, ValueFromPipeline) - - `Get-PSResource` (Name param, ValueFromPipeline) - - `Install-PSResource` (Name param, ValueFromPipeline) - - `Publish-PSResource` (None) - - `Save-PSResource` (Name param, ValueFromPipeline) - - `Uninstall-PSResource` (Name param, ValueFromPipeline) - - `Update-PSResource` (Name param, ValueFromPipeline) - - `Get-PSResourceRepository` (Name param, ValueFromPipeline) - - `Set-PSResourceRepository` (Name param, ValueFromPipeline) - - `Register-PSResourceRepository` (None) - - `Unregister-PSResourceRepository` (Name param, ValueFromPipelineByPropertyName) + - `Find-PSResource` (Name param, ValueFromPipeline) + - `Get-PSResource` (Name param, ValueFromPipeline) + - `Install-PSResource` (Name param, ValueFromPipeline) + - `Publish-PSResource` (None) + - `Save-PSResource` (Name param, ValueFromPipeline) + - `Uninstall-PSResource` (Name param, ValueFromPipeline) + - `Update-PSResource` (Name param, ValueFromPipeline) + - `Get-PSResourceRepository` (Name param, ValueFromPipeline) + - `Set-PSResourceRepository` (Name param, ValueFromPipeline) + - `Register-PSResourceRepository` (None) + - `Unregister-PSResourceRepository` (Name param, ValueFromPipelineByPropertyName) - Implement `-Tag` parameter set for `Find-PSResource` (i.e `Find-PSResource -Tag 'JSON'`) - Implement `-Type` parameter set for `Find-PSResource` (i.e `Find-PSResource -Type Module`) - Implement CommandName and DSCResourceName parameter sets for `Find-PSResource` (i.e `Find-PSResource -CommandName "Get-TargetResource"`). diff --git a/CHANGELOG/1.1.md b/CHANGELOG/1.1.md index fe2b73472..d8b1ceb50 100644 --- a/CHANGELOG/1.1.md +++ b/CHANGELOG/1.1.md @@ -5,9 +5,11 @@ ## 1.2.0-preview1 ### New Features + - Dependency support for PSResources in v3 repositories (#1778 Thanks @o-l-a-v!) ### Bug Fix + - Updated dependencies and added connection timeout to improve CI tests reliability (#1829) - Improvements in `ContainerRegistry` repositories in listing repository catalog (#1831) - Wildcard attribute added to `-Repository` parameter of `Install-PSResource` (#1808) diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 53d1677b2..6e4f6a49f 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,19 +1,20 @@ ## ## [1.1.0-rc3](https://github.com/PowerShell/PSResourceGet/compare/v1.1.0-RC2...v1.1.0-rc3) - 2024-11-15 ### Bug Fix -- Include missing commits +- Include missing commits ## [1.1.0-RC2](https://github.com/PowerShell/PSResourceGet/compare/v1.1.0-RC1...v1.1.0-RC2) - 2024-10-30 ### New Features + - Full Microsoft Artifact Registry integration (#1741) ### Bug Fixes - Update to use OCI v2 APIs for Container Registry (#1737) - Bug fixes for finding and installing from local repositories on Linux machines (#1738) -- Bug fix for finding package name with 4 part version from local repositories (#1739) +- Bug fix for finding package name with 4 part version from local repositories (#1739) # Preview Changelog diff --git a/Examples/FindRepositorySearchingExamples.md b/Examples/FindRepositorySearchingExamples.md index 0dc7015be..92932f310 100644 --- a/Examples/FindRepositorySearchingExamples.md +++ b/Examples/FindRepositorySearchingExamples.md @@ -1,5 +1,5 @@ -# Examples for `Find-PSResource` searching through repositories. +# Examples for `Find-PSResource` searching through repositories These examples will go through a number of scenarios related to `Find-PSResource` searching through repositories to show what the expected outcome will be. `Find-PSResource` will return resources from all repositories that match the criteria specified. In all these examples, the repositories registered and their priorities are as follows: @@ -17,103 +17,128 @@ Note that PSGallery has a lower priority than NuGetGallery. 1) Searching with only a package name specified, eg: `Find-PSResource 'TestModule'` or `Find-PSResource 'TestModule' -Repository '*'` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from both 'PSGallery' and 'NuGetGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'NuGetGallery'. * When the package exists in neither repository: + ``` Find-PSResource: Package 'TestModule' could not be found in any registered repositories. ``` + 2) Searching with a package name and a repository specified, eg: `Find-PSResource 'TestModule' -Repository PSGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Find-PSResource: Package with name 'TestModule' could not be found in repository 'PSGallery'. ``` + * When the package exists in neither repository: + ``` Find-PSResource: Package with name 'TestModule' could not be found in repository 'PSGallery'. ``` - + 3) Searching with a package name specified and wildcard repository, eg: `Find-PSResource 'TestModule' -Repository *Gallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'NuGetGallery'. - + * When the package exists in neither repository: + ``` Find-PSResource: Package 'TestModule' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` - + 4) Searching with a package name specified and multiple repository names specified, eg: `Find-PSResource 'TestModule' -Repository PSGallery, NuGetGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -121,10 +146,11 @@ Note that PSGallery has a lower priority than NuGetGallery. Find-PSResource: Package with name 'TestModule' could not be found in repository 'NuGetGallery'. ``` + Should return 'TestModule' from 'PSGallery'. - - + * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -132,18 +158,20 @@ Note that PSGallery has a lower priority than NuGetGallery. Find-PSResource: Package with name 'TestModule' could not be found in repository 'PSGallery'. ``` + Should return 'TestModule' from 'NuGetGallery'. - - + * When the package is in neither repository: + ``` Find-PSResource: Package with name 'TestModule' could not be found in repository 'PSGallery'. Find-PSResource: Package with name 'TestModule' could not be found in repository 'NuGetGallery'. ``` - + 5) Searching with a package name specified and both a repository name specified AND a repository name with a wildcard, eg: `Find-PSResource 'TestModule' -Repository *Gallery, otherRepository` * This scenario is not supported due to the ambiguity that arises when a repository with a wildcard in its name is specified as well as a repository with a specific name. The command will display the following error: + ``` Find-PSResource: Repository name with wildcard is not allowed when another repository without wildcard is specified. ``` @@ -154,31 +182,38 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. 1) Searching with only a tag specified, eg: `Find-PSResource -Tag 'Tag1'` or `Find-PSResource -Tag 'Tag1' -Repository '*'` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from both 'PSGallery' and 'NuGetGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'NuGetGallery'. * When the package exists in neither repository: + ``` Find-PSResource: Package with Tags 'Tag1' could not be found in any registered repositories. ``` @@ -186,44 +221,53 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. * When the package exists in both repositories and multiple existing tags are specified: eg: `Find-PSResource -Tag 'Tag1','Tag2'` or `Find-PSResource -Tag 'Tag1','Tag2' -Repository '*'` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from both 'PSGallery' and 'NuGetGallery'. - + * When the package exists in both repositories and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'Tag1','NonExistantTag'` or `Find-PSResource -Tag 'Tag1','NonExistantTag' -Repository '*'` + ``` Find-PSResource: Package with Tags 'Tag1, NonExistantTag' could not be found in any registered repositories. ``` 2) Searching with a tag and a repository specified, eg: `Find-PSResource -Tag 'Tag1' -Repository PSGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Package with Tags 'Tag1' could not be found in repository 'PSGallery'. ``` * When the package exists in neither repository: + ``` Package with Tags 'Tag1' could not be found in repository 'PSGallery'. ``` @@ -231,47 +275,57 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple existing tags are specified: eg: `Find-PSResource -Tag 'Tag1','Tag2' -Repository PSGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from both 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'Tag1','NonExistantTag' -Repository PSGallery` + ``` Find-PSResource: Package with Tags 'Tag1, NonExistantTag' could not be found in repository 'PSGallery'. ``` 3) Searching with a tag specified and wildcard repository, eg: `Find-PSResource -Tag 'Tag1' -Repository *Gallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'NuGetGallery'. - + * When the package exists in neither repository: + ``` Find-PSResource: Package with Tags 'Tag1' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` @@ -279,17 +333,20 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. * When the package exists in both repositories and multiple existing tags are specified: eg: `Find-PSResource -Tag 'Tag1','Tag2' -Repository *Gallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. * When the package exists in both repositories and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'Tag1','NonExistantTag' -Repository *Gallery` + ``` Find-PSResource: Package with Tags 'Tag1, NonExistantTag' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` @@ -297,15 +354,18 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. 4) Searching with a tag specified and multiple repository names specified, eg: `Find-PSResource -Tag 'Tag1' -Repository PSGallery, NuGetGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -313,10 +373,11 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. Find-PSResource: Package with Tags 'Tag1' could not be found in repository 'NuGetGallery'. ``` + Should return 'TestModule' from 'PSGallery'. - - + * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -324,10 +385,11 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. Find-PSResource: Package with Tags 'Tag1' could not be found in repository 'PSGallery'. ``` + Should return 'TestModule' from 'NuGetGallery'. - - + * When the package is in neither repository: + ``` Find-PSResource: Package with Tags 'Tag1' could not be found in repository 'PSGallery'. Find-PSResource: Package with Tags 'Tag1' could not be found in repository 'NuGetGallery'. @@ -336,17 +398,20 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. * When the package exists in both repositories and multiple existing tags are specified: eg: `Find-PSResource -Tag 'Tag1','Tag2' -Repository PSGallery, NuGetGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery TestModule 1.0.0.0 NuGetGallery ``` + Should return 'TestModule' from 'PSGallery' and 'NuGetGallery'. * When the package exists in both repositories and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'Tag1','NonExistantTag' -Repository PSGallery, NuGetGallery` + ``` Find-PSResource: Package with Tags 'Tag1, NonExistantTag' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` @@ -354,6 +419,7 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. 5) Searching with a tag specified and both a repository name specified AND a repository name with a wildcard, eg: `Find-PSResource -Tag 'Tag1' -Repository *Gallery, otherRepository` * This scenario is not supported due to the ambiguity that arises when a repository with a wildcard in its name is specified as well as a repository with a specific name. The command will display the following error: + ``` Find-PSResource: Repository name with wildcard is not allowed when another repository without wildcard is specified. ``` @@ -364,74 +430,90 @@ In these examples, the package TestModule has the following command names (i.e t 1) Searching with only a Command name specified, eg: `Find-PSResource -CommandName 'Get-MyCommand1'` or `Find-PSResource -CommandName 'Get-MyCommand1' -Repository '*'` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1' could not be found in any registered repositories. ``` + Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in neither repository: + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1' could not be found in any registered repositories. ``` + Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in both repositories and multiple existing Command names are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','Get-MyCommand2'` or `Find-PSResource -CommandName 'Get-MyCommand1','Get-MyCommand2' -Repository '*'` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from both 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. - * When the package exists in both repositories and multiple Command names (existing and non-existant) are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','NonExistantCommand'` or `Find-PSResource -CommandName 'Get-MyCommand1','NonExistantCommand' -Repository '*'` + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1, NonExistantCommand' could not be found in any registered repositories. ``` 2) Searching with a Command name and a repository specified, eg: `Find-PSResource -CommandName 'Get-MyCommand1' -Repository PSGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Package with CommandName 'Get-MyCommand1' could not be found in repository 'PSGallery'. ``` * When the package exists in neither repository: + ``` Package with CommandName 'Get-MyCommand1' could not be found in repository 'PSGallery'. ``` @@ -439,44 +521,54 @@ In these examples, the package TestModule has the following command names (i.e t * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple existing tags are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','Get-MyCommand2' -Repository PSGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','NonExistantCommand' -Repository PSGallery` + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1, Get-MyCommand2' could not be found in repository 'PSGallery'. ``` 3) Searching with a Command name specified and wildcard repository, eg: `Find-PSResource -CommandName 'Get-MyCommand1' -Repository *Gallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1' could not be found in any registered repositories. ``` + Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in neither repository: + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` @@ -484,31 +576,37 @@ In these examples, the package TestModule has the following command names (i.e t * When the package exists in both repositories and multiple existing Command names are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','Get-MyCommand2' -Repository *Gallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in both repositories and multiple Command names (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'Get-MyCommand1','NonExistantCommand' -Repository *Gallery` + ``` Find-PSResource: Package with CommandName 'Get-MyCommand1, NonExistantCommand' could not be found in registered repositories: 'PSGallery, NuGetGallery'. - ``` - + ``` + 4) Searching with a Command name specified and multiple repository names specified, eg: `Find-PSResource -CommandName 'Get-MyCommand1' -Repository PSGallery, NuGetGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -516,25 +614,30 @@ In these examples, the package TestModule has the following command names (i.e t Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-CommandName` for NuGetGallery repository is not supported, it will not be searched and error written out. - + * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): - ``` + + ``` Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-CommandName` for NuGetGallery repository is not supported, it will not be searched and error written out. - - + * When the package is in neither repository: + ``` Find-PSResource: Package with Command 'Get-MyCommand1' could not be found in repository 'PSGallery'. Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-CommandName` for NuGetGallery repository, it will not be searched and error written out. * When the package exists in both repositories and multiple existing Command names are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','Get-MyCommand2' -Repository PSGallery, NuGetGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -542,21 +645,24 @@ In these examples, the package TestModule has the following command names (i.e t Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` - Since searching with `-CommandName` for NuGetGallery repository, it will not be searched and error written out. + Since searching with `-CommandName` for NuGetGallery repository, it will not be searched and error written out. * When the package exists in both repositories and multiple Command names (existing and non-existant) are specified: eg: `Find-PSResource -CommandName 'Get-MyCommand1','NonExistantCommand' -Repository PSGallery, NuGetGallery` + ``` Find-PSResource: Package with Command 'Get-MyCommand1' could not be found in repository 'PSGallery'. Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-CommandName` for NuGetGallery repository, it will not be searched and error written out. - + 5) Searching with a Command name specified and both a repository name specified AND a repository name with a wildcard, eg: `Find-PSResource -CommandName 'Get-MyCommand1' -Repository *Gallery, otherRepository` * This scenario is not supported due to the ambiguity that arises when a repository with a wildcard in its name is specified as well as a repository with a specific name. The command will display the following error: + ``` Find-PSResource: Repository name with wildcard is not allowed when another repository without wildcard is specified. ``` @@ -567,74 +673,90 @@ In these examples, the package TestModule has the following DscResource names (i 1) Searching with only a DscResource name specified, eg: `Find-PSResource -DscResourceName 'MyDscResource1'` or `Find-PSResource -DscResourceName 'MyDscResource1' -Repository '*'` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1' could not be found in any registered repositories. ``` + Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in neither repository: + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1' could not be found in any registered repositories. ``` + Since searching with `-DSCResourceName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in both repositories and multiple existing DSCResource names are specified: eg: `Find-PSResource -DSCResourceName 'MyDscResource1','MyDscResource2'` or `Find-PSResource -DSCResourceName 'MyDscResource1', 'MyDscResource2' -Repository '*'` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from both 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. - * When the package exists in both repositories and multiple DscResource names (existing and non-existant) are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','NonExistantDscResource'` or `Find-PSResource -DSCResourceName 'MyDscResource1','NonExistantDscResource' -Repository '*'` + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1, NonExistantDscResource' could not be found in any registered repositories. ``` 2) Searching with a DscResource name and a repository specified, eg: `Find-PSResource -DscResourceName 'MyDscResource1' -Repository PSGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Package with DscResourceName 'MyDscResource1' could not be found in repository 'PSGallery'. ``` * When the package exists in neither repository: + ``` Package with DSCResourceName 'MyDscResource1' could not be found in repository 'PSGallery'. ``` @@ -642,44 +764,54 @@ In these examples, the package TestModule has the following DscResource names (i * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple existing tags are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','MyDscResource2' -Repository PSGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery) and multiple tags (existing and non-existant) are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','NonExistantDscResource' -Repository PSGallery` + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1, MyDscResource2' could not be found in repository 'PSGallery'. ``` 3) Searching with a DscResource name specified and wildcard repository, eg: `Find-PSResource -DscResourceName 'MyDscResource1' -Repository *Gallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1' could not be found in any registered repositories. ``` + Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in neither repository: + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1' could not be found in registered repositories: 'PSGallery, NuGetGallery'. ``` @@ -687,31 +819,37 @@ In these examples, the package TestModule has the following DscResource names (i * When the package exists in both repositories and multiple existing DscResource names are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','MyDscResource2' -Repository *Gallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. * When the package exists in both repositories and multiple DscResource names (existing and non-existant) are specified: eg: `Find-PSResource -Tag 'MyDscResource1','NonExistantDscResource' -Repository *Gallery` + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1, NonExistantDscResource' could not be found in registered repositories: 'PSGallery, NuGetGallery'. - ``` - + ``` + 4) Searching with a DscResource name specified and multiple repository names specified, eg: `Find-PSResource -DscResourceName 'MyDscResource1' -Repository PSGallery, NuGetGallery` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will be skipped. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -719,25 +857,30 @@ In these examples, the package TestModule has the following DscResource names (i Find-PSResource: Find by DscResourceName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Should return 'TestModule' from 'PSGallery'. Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will not be searched and error written out. - + * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): - ``` + + ``` Find-PSResource: Find by DscResourceName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-DscResourceName` for NuGetGallery repository is not supported, it will not be searched and error written out. - - + * When the package is in neither repository: + ``` Find-PSResource: Package with DSCResourceName 'MyDscResource1' could not be found in repository 'PSGallery'. Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-DscResourceName` for NuGetGallery repository, it will not be searched and error written out. * When the package exists in both repositories and multiple existing DscResource names are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','MyDscResource2' -Repository PSGallery, NuGetGallery` + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -745,21 +888,24 @@ In these examples, the package TestModule has the following DscResource names (i Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` - Since searching with `-DscResourceName` for NuGetGallery repository, it will not be searched and error written out. + Since searching with `-DscResourceName` for NuGetGallery repository, it will not be searched and error written out. * When the package exists in both repositories and multiple DscResource names (existing and non-existant) are specified: eg: `Find-PSResource -DscResourceName 'MyDscResource1','NonExistantDscResource' -Repository PSGallery, NuGetGallery` + ``` Find-PSResource: Package with DscResource 'MyDscResource1' could not be found in repository 'PSGallery'. Find-PSResource: Find by CommandName or DSCResource is not supported for the V3 server protocol repository 'NuGetGallery'. ``` + Since searching with `-DscResourceName` for NuGetGallery repository, it will not be searched and error written out. - + 5) Searching with a DscResource name specified and both a repository name specified AND a repository name with a wildcard, eg: `Find-PSResource -DscResourceName 'MyDscResource1' -Repository *Gallery, otherRepository` * This scenario is not supported due to the ambiguity that arises when a repository with a wildcard in its name is specified as well as a repository with a specific name. The command will display the following error: + ``` Find-PSResource: Repository name with wildcard is not allowed when another repository without wildcard is specified. - ``` \ No newline at end of file + ``` diff --git a/Examples/InstallRepositorySearchingExamples.md b/Examples/InstallRepositorySearchingExamples.md index f49ed5bda..13537f1fc 100644 --- a/Examples/InstallRepositorySearchingExamples.md +++ b/Examples/InstallRepositorySearchingExamples.md @@ -1,5 +1,5 @@ -# Examples for `Install-PSResource` searching through repositories. +# Examples for `Install-PSResource` searching through repositories These examples will go through a number of scenarios related to `Install-PSResource` searching through repositories to install from to show what the expected outcome will be. `Install-PSResource` will install the resource from the repository with the highest priority (i.e. the smallest number) that matches the criteria specified. In all these examples, the repositories registered and their priorities are as follows: @@ -13,123 +13,153 @@ NuGetGallery https://api.nuget.org/v3/index.json True 60 1) Installing with only a package name specified, eg: `Install-PSResource 'TestModule' -PassThru` or `Install-PSResource 'TestModule' -Repository '*' -PassThru` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should install 'TestModule' from 'NuGetGallery'. * When the package exists in neither repository: + ``` Install-PSResource: Package(s) 'TestModule' could not be installed from registered repositories 'PSGallery, NuGetGallery'. ``` + 2) Installing with a package name and a repository specified, eg: `Install-PSResource 'TestModule' -Repository PSGallery -PassThru` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Install-PSResource: Package(s) 'TestModule' could not be installed from repository 'PSGallery'. ``` + * When the package exists in neither repository: + ``` Install-PSResource: Package(s) 'TestModule' could not be installed from repository 'PSGallery'. ``` - + 3) Installing with a package name specified and wildcard repository, eg: `Install-PSResource 'TestModule' -Repository *Gallery -PassThru` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the first repository (PSSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (PSGallery), but not the first (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should install 'TestModule' from 'NuGetGallery'. - + * When the package exists in neither repository: + ``` Install-PSResource: Package(s) 'TestModule' could not be installed from registered repositories 'PSGallery, NuGetGallery'. ``` - + 4) Installing with a package name specified and multiple repository names specified, eg: `Install-PSResource 'TestModule' -Repository PSGallery, NuGetGallery -PassThru` * When the package exists in both repositories: + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the first repository (PSGallery), but not the second (NuGetGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 PSGallery ``` + Should install 'TestModule' from 'PSGallery'. - + * When the package exists in the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- TestModule 1.0.0.0 NuGetGallery ``` + Should install 'TestModule' from 'NuGetGallery'. - + * When the package exists in neither repository: + ``` Install-PSResource: Package(s) 'TestModule' could not be installed from registered repositories 'PSGallery, NuGetGallery'. ``` - + 5) Installing with a package name specified and both a repository name specified AND a repository name with a wildcard, eg: `Install-PSResource 'TestModule' -Repository *Gallery, otherRepository`. * This scenario is not supported due to the ambiguity that arises when a repository with a wildcard in its name is specified as well as a repository with a specific name. The command will display the following error: + ``` Install-PSResource: Repository name with wildcard is not allowed when another repository without wildcard is specified. - ``` \ No newline at end of file + ``` diff --git a/README.md b/README.md index a0ca6c443..3cbee76c0 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ * If you were familiar with the PowerShellGet 3.0 project, we renamed the module to be PSResourceGet, for more information please read [this blog](https://devblogs.microsoft.com/powershell/powershellget-in-powershell-7-4-updates/). * If you would like to open a PR please open an issue first so that necessary discussion can take place. - * Please open an issue for any feature requests, bug reports, or questions for PSResourceGet. - * See the [Contributing Quickstart Guide](#contributing-quickstart-guide) section. + * Please open an issue for any feature requests, bug reports, or questions for PSResourceGet. + * See the [Contributing Quickstart Guide](#contributing-quickstart-guide) section. * Please note, the repository for PowerShellGet v2 is available at [PowerShell/PowerShellGetv2](https://github.com/PowerShell/PowerShellGetv2). * The repository for the PowerShellGet v3, the compatibility layer between PowerShellGet v2 and PSResourceGet, is available at [PowerShell/PowerShellGet](https://github.com/PowerShell/PowerShellGet). @@ -40,11 +40,14 @@ Please use the [PowerShell Gallery](https://www.powershellgallery.com) to get th ### Get the source code * Download the latest source code from the release page () OR clone the repository using git. + ```powershell PS > cd 'C:\Repos' PS C:\Repos> git clone https://github.com/PowerShell/PSResourceGet ``` + * Navigate to the local repository directory + ```powershell PS C:\> cd c:\Repos\PSResourceGet PS C:\Repos\PSResourceGet> @@ -53,6 +56,7 @@ Please use the [PowerShell Gallery](https://www.powershellgallery.com) to get th ### Build the project Note: Please ensure you have the exact version of the .NET SDK installed. The current version can be found in the [global.json](https://github.com/PowerShell/PSResourceGet/blob/master/global.json) and installed from the [.NET website](https://dotnet.microsoft.com/en-us/download). + ```powershell # Build for the net472 framework PS C:\Repos\PSResourceGet> .\build.ps1 -Clean -Build -BuildConfiguration Debug -BuildFramework net472 @@ -61,10 +65,13 @@ Note: Please ensure you have the exact version of the .NET SDK installed. The c ### Run functional tests * Run all tests + ```powershell PS C:\Repos\PSResourceGet> Invoke-Pester ``` + * Run an individual test + ```powershell PS C:\Repos\PSResourceGet> Invoke-Pester ``` @@ -80,8 +87,10 @@ C:\> Import-Module C:\Repos\PSResourceGet\out\PSResourceGet c:\> PowerShell C:\> Import-Module C:\Repos\PSResourceGet\out\PSResourceGet\PSResourceGet.psd1 ``` -## Module Support Lifecycle -Microsoft.PowerShell.PSResourceGet follows the support lifecycle of the version of PowerShell that it ships in. + +## Module Support Lifecycle + +Microsoft.PowerShell.PSResourceGet follows the support lifecycle of the version of PowerShell that it ships in. For example, PSResourceGet 1.0.x shipped in PowerShell 7.4 which is an LTS release so it will be supported for 3 years. Preview versions of the module, or versions that ship in preview versions of PowerShell are not supported. Versions of PSResourceGet that do not ship in a version of PowerShell will be fixed forward. diff --git a/SECURITY.md b/SECURITY.md index f941d308b..2f60759e2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,17 +14,17 @@ Instead, please report them to the Microsoft Security Response Center (MSRC) at If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp). -You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: - * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) - * Full paths of source file(s) related to the manifestation of the issue - * The location of the affected source code (tag/branch/commit or direct URL) - * Any special configuration required to reproduce the issue - * Step-by-step instructions to reproduce the issue - * Proof-of-concept or exploit code (if possible) - * Impact of the issue, including how an attacker might exploit the issue +* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) +* Full paths of source file(s) related to the manifestation of the issue +* The location of the affected source code (tag/branch/commit or direct URL) +* Any special configuration required to reproduce the issue +* Step-by-step instructions to reproduce the issue +* Proof-of-concept or exploit code (if possible) +* Impact of the issue, including how an attacker might exploit the issue This information will help us triage your report more quickly. diff --git a/global.json b/global.json index fb6d6a3df..e5f41726d 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { - "sdk": { - "version": "8.0.411" - } + "sdk": { + "version": "8.0.411" + } } diff --git a/src/InstallPSResourceGetPolicyDefinitions.ps1 b/src/InstallPSResourceGetPolicyDefinitions.ps1 index e0f2d15d4..d5e95fc2a 100644 --- a/src/InstallPSResourceGetPolicyDefinitions.ps1 +++ b/src/InstallPSResourceGetPolicyDefinitions.ps1 @@ -19,8 +19,7 @@ param Set-StrictMode -Version 3.0 $ErrorActionPreference = 'Stop' -function Test-Elevated -{ +function Test-Elevated { [CmdletBinding()] [OutputType([bool])] Param() @@ -32,18 +31,15 @@ function Test-Elevated } $IsWindowsOs = $PSHOME.EndsWith('\WindowsPowerShell\v1.0', [System.StringComparison]::OrdinalIgnoreCase) -or $IsWindows -if (-not $IsWindowsOs) -{ +if (-not $IsWindowsOs) { throw 'This script must be run on Windows.' } -if (-not (Test-Elevated)) -{ +if (-not (Test-Elevated)) { throw 'This script must be run from an elevated process.' } -if ([System.Management.Automation.Platform]::IsNanoServer) -{ +if ([System.Management.Automation.Platform]::IsNanoServer) { throw 'Group policy definitions are not supported on Nano Server.' } @@ -55,10 +51,8 @@ $admxTargetPath = Join-Path -Path $env:WINDIR -ChildPath "PolicyDefinitions" $admlTargetPath = Join-Path -Path $admxTargetPath -ChildPath "en-US" $files = @($admx, $adml) -foreach ($file in $files) -{ - if (-not (Test-Path -Path $file)) - { +foreach ($file in $files) { + if (-not (Test-Path -Path $file)) { throw "Could not find $($file.Name) at $Path" } } @@ -66,23 +60,17 @@ foreach ($file in $files) Write-Verbose "Copying $admx to $admxTargetPath" Copy-Item -Path $admx -Destination $admxTargetPath -Force $admxTargetFullPath = Join-Path -Path $admxTargetPath -ChildPath $admxName -if (Test-Path -Path $admxTargetFullPath) -{ +if (Test-Path -Path $admxTargetFullPath) { Write-Verbose "$admxName was installed successfully" -} -else -{ +} else { Write-Error "Could not install $admxName" } Write-Verbose "Copying $adml to $admlTargetPath" Copy-Item -Path $adml -Destination $admlTargetPath -Force $admlTargetFullPath = Join-Path -Path $admlTargetPath -ChildPath $admlName -if (Test-Path -Path $admlTargetFullPath) -{ +if (Test-Path -Path $admlTargetFullPath) { Write-Verbose "$admlName was installed successfully" -} -else -{ +} else { Write-Error "Could not install $admlName" } diff --git a/src/Microsoft.PowerShell.PSResourceGet.psd1 b/src/Microsoft.PowerShell.PSResourceGet.psd1 index 5ff9f3d13..01947560b 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psd1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psd1 @@ -37,14 +37,14 @@ FunctionsToExport = @( 'Import-PSGetRepository' ) - VariablesToExport = 'PSGetPath' - AliasesToExport = @( + VariablesToExport = 'PSGetPath' + AliasesToExport = @( 'Get-PSResource', 'fdres', 'isres', 'pbres', 'udres') - PrivateData = @{ + PrivateData = @{ PSData = @{ Prerelease = 'preview1' Tags = @('PackageManagement', @@ -103,7 +103,7 @@ - Update to use OCI v2 APIs for Container Registry (#1737) - Bug fixes for finding and installing from local repositories on Linux machines (#1738) -- Bug fix for finding package name with 4 part version from local repositories (#1739) +- Bug fix for finding package name with 4 part version from local repositories (#1739) ## 1.1.0-RC1 @@ -115,7 +115,7 @@ - Fix packaging name matching when searching in local repositories (#1731) - `Compress-PSResource` `-PassThru` now passes `FileInfo` instead of string (#1720) -- Fix for `Compress-PSResource` not properly compressing scripts (#1719) +- Fix for `Compress-PSResource` not properly compressing scripts (#1719) - Add `AcceptLicense` to Save-PSResource (#1718 Thanks @o-l-a-v!) - Better support for NuGet v2 feeds (#1713 Thanks @o-l-a-v!) - Better handling of `-WhatIf` support in `Install-PSResource` (#1531 Thanks @o-l-a-v!) @@ -141,7 +141,7 @@ ### New Features -- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, +- Support for Azure Container Registries (#1495, #1497-#1499, #1501, #1502, #1505, #1522, #1545, #1548, #1550, #1554, #1560, #1567, #1573, #1576, #1587, #1588, #1589, #1594, #1598, #1600, #1602, #1604, #1615) ### Bug Fixes @@ -222,7 +222,7 @@ - Bug fix Artifactory v2 endpoint failures (#1428) - Bug fix Artifactory v3 endpoint failures (#1427) - Bug fix `-RequiredResource` silent failures (#1426) -- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) +- Bug fix for v2 repository returning extra packages for `-Tag` based search with `-Prerelease` (#1405) See change log (CHANGELOG) at https://github.com/PowerShell/PSResourceGet '@ diff --git a/src/Microsoft.PowerShell.PSResourceGet.psm1 b/src/Microsoft.PowerShell.PSResourceGet.psm1 index 3e477cb1f..b1d2d1978 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psm1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psm1 @@ -15,8 +15,7 @@ function Import-PSGetRepository { $IsOSWindows = $Runtime::IsOSPlatform($OSPlatform::Windows) if ($IsOSWindows) { $PSGetAppLocalPath = Microsoft.PowerShell.Management\Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\Windows\PowerShell\PowerShellGet\' - } - else { + } else { $PSGetAppLocalPath = Microsoft.PowerShell.Management\Join-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('CACHE')) -ChildPath 'PowerShellGet' } $PSRepositoriesFilePath = Microsoft.PowerShell.Management\Join-Path -Path $PSGetAppLocalPath -ChildPath "PSRepositories.xml" @@ -27,7 +26,7 @@ function Import-PSGetRepository { if ($PSGetRepositories.Count) { $repos = @( $PSGetRepositories.Values | - Microsoft.PowerShell.Core\Where-Object {$_.PackageManagementProvider -eq 'NuGet'-and $_.Name -ne 'PSGallery'} | + Microsoft.PowerShell.Core\Where-Object { $_.PackageManagementProvider -eq 'NuGet' -and $_.Name -ne 'PSGallery' } | Microsoft.PowerShell.Utility\Select-Object Name, Trusted, SourceLocation ) @@ -37,25 +36,23 @@ function Import-PSGetRepository { $repos | Microsoft.PowerShell.Core\ForEach-Object { try { $message = 'Registering {0} at {1} -Trusted:${2} -Force:${3}.' -f $_.Name, - $_.SourceLocation, $_.Trusted, $Force + $_.SourceLocation, $_.Trusted, $Force if ($PSCmdlet.ShouldProcess($message, $_.Name, 'Register-PSResourceRepository')) { $registerPSResourceRepositorySplat = @{ - Name = $_.Name - Uri = $_.SourceLocation - Trusted = $_.Trusted - PassThru = $true - Force = $Force - ApiVersion = if ([Uri]::new($_.SourceLocation).Scheme -eq 'file') {'local'} else {'v2'} + Name = $_.Name + Uri = $_.SourceLocation + Trusted = $_.Trusted + PassThru = $true + Force = $Force + ApiVersion = if ([Uri]::new($_.SourceLocation).Scheme -eq 'file') { 'local' } else { 'v2' } } Register-PSResourceRepository @registerPSResourceRepositorySplat } - } - catch [System.Management.Automation.PSInvalidOperationException] { + } catch [System.Management.Automation.PSInvalidOperationException] { if ($_.Exception.Message -match 'already exists') { Microsoft.PowerShell.Utility\Write-Warning $_.Exception.Message Microsoft.PowerShell.Utility\Write-Warning 'Use the -Force switch to overwrite existing repositories.' - } - else { + } else { throw $_.Exception } } diff --git a/src/code/ContainerRegistryInfo.cs b/src/code/ContainerRegistryInfo.cs index 6d8ff5c32..b1d7d64df 100644 --- a/src/code/ContainerRegistryInfo.cs +++ b/src/code/ContainerRegistryInfo.cs @@ -7,43 +7,43 @@ namespace Microsoft.PowerShell.PSResourceGet.UtilClasses { - public sealed class ContainerRegistryInfo - { - #region Properties + public sealed class ContainerRegistryInfo + { + #region Properties - public string Name { get; } - public string Metadata { get; } - public ResourceType ResourceType { get; } + public string Name { get; } + public string Metadata { get; } + public ResourceType ResourceType { get; } - #endregion + #endregion - #region Constructors + #region Constructors - internal ContainerRegistryInfo(string name, string metadata, string resourceType) + internal ContainerRegistryInfo(string name, string metadata, string resourceType) - { - Name = name ?? string.Empty; - Metadata = metadata ?? string.Empty; - ResourceType = string.IsNullOrWhiteSpace(resourceType) ? ResourceType.None : - (ResourceType)Enum.Parse(typeof(ResourceType), resourceType, ignoreCase: true); - } + { + Name = name ?? string.Empty; + Metadata = metadata ?? string.Empty; + ResourceType = string.IsNullOrWhiteSpace(resourceType) ? ResourceType.None : + (ResourceType)Enum.Parse(typeof(ResourceType), resourceType, ignoreCase: true); + } #endregion #region Methods internal Hashtable ToHashtable() - { - Hashtable hashtable = new Hashtable - { - { "Name", Name }, - { "Metadata", Metadata }, - { "ResourceType", ResourceType } - }; + { + Hashtable hashtable = new Hashtable + { + { "Name", Name }, + { "Metadata", Metadata }, + { "ResourceType", ResourceType } + }; return hashtable; - } + } #endregion } diff --git a/src/code/ContainerRegistryServerAPICalls.cs b/src/code/ContainerRegistryServerAPICalls.cs index 5977d4adf..0dfa929be 100644 --- a/src/code/ContainerRegistryServerAPICalls.cs +++ b/src/code/ContainerRegistryServerAPICalls.cs @@ -524,11 +524,11 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistyUrl, boo } catch (HttpRequestException hre) { - errRecord = new ErrorRecord( - hre, - "RegistryAnonymousAcquireError", - ErrorCategory.ConnectionError, - this); + errRecord = new ErrorRecord( + hre, + "RegistryAnonymousAcquireError", + ErrorCategory.ConnectionError, + this); return false; } @@ -1239,7 +1239,7 @@ internal bool PushNupkgContainerRegistry( _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::PushNupkgContainerRegistry()"); // if isNupkgPathSpecified, then we need to publish the original .nupkg file, as it may be signed - string fullNupkgFile = isNupkgPathSpecified ? originalNupkgPath : System.IO.Path.Combine(outputNupkgDir, packageName + "." + packageVersion.ToNormalizedString() + ".nupkg"); + string fullNupkgFile = isNupkgPathSpecified ? originalNupkgPath : System.IO.Path.Combine(outputNupkgDir, packageName + "." + packageVersion.ToNormalizedString() + ".nupkg"); string pkgNameForUpload = string.IsNullOrEmpty(modulePrefix) ? packageName : modulePrefix + "/" + packageName; string packageNameLowercase = pkgNameForUpload.ToLower(); diff --git a/src/code/FindResults.cs b/src/code/FindResults.cs index f0cb2127e..c6fbe46ce 100644 --- a/src/code/FindResults.cs +++ b/src/code/FindResults.cs @@ -22,13 +22,13 @@ public enum FindResponseType public sealed class FindResults { public string[] StringResponse { get; private set; } = Utils.EmptyStrArray; - public Hashtable[] HashtableResponse { get; private set; } = new Hashtable[]{}; + public Hashtable[] HashtableResponse { get; private set; } = new Hashtable[] { }; public FindResponseType ResponseType { get; set; } public FindResults() { this.StringResponse = Utils.EmptyStrArray; - this.HashtableResponse = new Hashtable[]{}; + this.HashtableResponse = new Hashtable[] { }; this.ResponseType = FindResponseType.None; } @@ -37,7 +37,7 @@ public FindResults(string[] stringResponse, Hashtable[] hashtableResponse, FindR this.StringResponse = stringResponse; this.HashtableResponse = hashtableResponse; this.ResponseType = responseType; - } + } public bool IsFindResultsEmpty() { diff --git a/src/code/GetHelper.cs b/src/code/GetHelper.cs index 636bd383a..54cd6c640 100644 --- a/src/code/GetHelper.cs +++ b/src/code/GetHelper.cs @@ -163,7 +163,7 @@ public IEnumerable FilterPkgPathsByVersion(VersionRange versionRange, Li foreach (string versionPath in versionsDirs) { _cmdletPassedIn.WriteDebug($"Searching through package version path: '{versionPath}'"); - if(!Utils.GetVersionForInstallPath(installedPkgPath: versionPath, + if (!Utils.GetVersionForInstallPath(installedPkgPath: versionPath, isModule: true, cmdletPassedIn: _cmdletPassedIn, out NuGetVersion pkgNugetVersion)) @@ -204,7 +204,7 @@ public IEnumerable FilterPkgPathsByVersion(VersionRange versionRange, Li // check to make sure it's within the version range. // script versions will be parsed from the script xml file PSResourceInfo scriptInfo = OutputPackageObject(pkgPath, _scriptDictionary); - if(!Utils.GetVersionForInstallPath(installedPkgPath: pkgPath, + if (!Utils.GetVersionForInstallPath(installedPkgPath: pkgPath, isModule: false, cmdletPassedIn: _cmdletPassedIn, out NuGetVersion pkgNugetVersion)) @@ -226,7 +226,7 @@ public IEnumerable FilterPkgPathsByVersion(VersionRange versionRange, Li } // Create package object for each found resource directory - public PSResourceInfo OutputPackageObject(string pkgPath, Dictionary scriptDictionary) + public PSResourceInfo OutputPackageObject(string pkgPath, Dictionary scriptDictionary) { // If the package path is in the deserialized script dictionary, just return that if (scriptDictionary.ContainsKey(pkgPath)) diff --git a/src/code/GetInstalledPSResource.cs b/src/code/GetInstalledPSResource.cs index dafd36400..3ab156772 100644 --- a/src/code/GetInstalledPSResource.cs +++ b/src/code/GetInstalledPSResource.cs @@ -119,7 +119,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - var namesToSearch = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool _); + var namesToSearch = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] errorMsgs, out bool _); foreach (string error in errorMsgs) { WriteError(new ErrorRecord( @@ -153,7 +153,7 @@ protected override void ProcessRecord() List pkgsNotFound = new List(); foreach (string name in namesToSearch) { - if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) + if (!pkgsFound.Contains(name, StringComparer.OrdinalIgnoreCase)) { if (name.Contains('*')) { diff --git a/src/code/GetPSScriptFileInfo.cs b/src/code/GetPSScriptFileInfo.cs index 2fa1c71e5..529a0c454 100644 --- a/src/code/GetPSScriptFileInfo.cs +++ b/src/code/GetPSScriptFileInfo.cs @@ -28,7 +28,7 @@ public sealed class GetPSScriptFileInfo : PSCmdlet #region Methods protected override void EndProcessing() - { + { if (!Path.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { ThrowTerminatingError(new ErrorRecord( @@ -64,7 +64,7 @@ protected override void EndProcessing() { exMessage += Environment.NewLine + error.Exception.Message; } - + ThrowTerminatingError(new ErrorRecord( new PSArgumentException(exMessage), "InvalidPSScriptFile", diff --git a/src/code/GroupPolicyRepositoryEnforcement.cs b/src/code/GroupPolicyRepositoryEnforcement.cs index ac4f7ee98..b68c340fa 100644 --- a/src/code/GroupPolicyRepositoryEnforcement.cs +++ b/src/code/GroupPolicyRepositoryEnforcement.cs @@ -96,7 +96,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) { bool isAllowed = false; - if(GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) + if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) { var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); @@ -146,7 +146,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) continue; } - var valueNames = psrgKey.GetValueNames(); + var valueNames = psrgKey.GetValueNames(); // This means it is disabled if (valueNames is null || valueNames.Length == 0 || valueNames.Length == 1 && valueNames[0].Equals("**delvals.", StringComparison.OrdinalIgnoreCase)) @@ -223,4 +223,4 @@ private static KeyValuePair ConvertRegValue(string regValue) } } } -} \ No newline at end of file +} diff --git a/src/code/IServerAPICalls.cs b/src/code/IServerAPICalls.cs index 74521866c..70c0f7f18 100644 --- a/src/code/IServerAPICalls.cs +++ b/src/code/IServerAPICalls.cs @@ -21,7 +21,7 @@ public interface IServerAPICalls /// Examples: Search -Tag "JSON" -Repository PSGallery /// FindResults FindTags(string[] tags, bool includePrerelease, ResourceType _type, out ErrorRecord errRecord); - + /// /// Find method which allows for searching for single name and returns latest version. /// Name: no wildcard support diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index d8af185f0..19e88b4a7 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -290,13 +290,14 @@ protected override void ProcessRecord() break; case InputObjectParameterSet: - foreach (var inputObj in InputObject) { + foreach (var inputObj in InputObject) + { string normalizedVersionString = Utils.GetNormalizedVersionString(inputObj.Version.ToString(), inputObj.Prerelease); ProcessInstallHelper( pkgNames: new string[] { inputObj.Name }, pkgVersion: normalizedVersionString, pkgPrerelease: inputObj.IsPrerelease, - pkgRepository: new string[]{ inputObj.Repository }, + pkgRepository: new string[] { inputObj.Repository }, pkgCredential: Credential, reqResourceParams: null); } @@ -497,7 +498,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) pkgNames: new string[] { pkgName }, pkgVersion: pkgVersion, pkgPrerelease: pkgParams.Prerelease, - pkgRepository: pkgParams.Repository != null ? new string[] { pkgParams.Repository } : new string[]{}, + pkgRepository: pkgParams.Repository != null ? new string[] { pkgParams.Repository } : new string[] { }, pkgCredential: pkgCredential, reqResourceParams: pkgParams); } @@ -506,7 +507,7 @@ private void RequiredResourceHelper(Hashtable reqResourceHash) private void ProcessInstallHelper(string[] pkgNames, string pkgVersion, bool pkgPrerelease, string[] pkgRepository, PSCredential pkgCredential, InstallPkgParams reqResourceParams) { WriteDebug("In InstallPSResource::ProcessInstallHelper()"); - var inputNameToInstall = Utils.ProcessNameWildcards(pkgNames, removeWildcardEntries:false, out string[] errorMsgs, out bool nameContainsWildcard); + var inputNameToInstall = Utils.ProcessNameWildcards(pkgNames, removeWildcardEntries: false, out string[] errorMsgs, out bool nameContainsWildcard); if (nameContainsWildcard) { WriteError(new ErrorRecord( diff --git a/src/code/InstallPkgParams.cs b/src/code/InstallPkgParams.cs index 7a1b8e986..26361a29e 100644 --- a/src/code/InstallPkgParams.cs +++ b/src/code/InstallPkgParams.cs @@ -11,7 +11,7 @@ public class InstallPkgParams public string Name { get; set; } public VersionRange Version { get; set; } public string Repository { get; set; } - public bool AcceptLicense { get; set; } + public bool AcceptLicense { get; set; } public bool Prerelease { get; set; } public ScopeType Scope { get; set; } public bool Quiet { get; set; } @@ -32,7 +32,7 @@ public void SetProperty(string propertyName, string propertyValue, out ErrorReco { ParameterParsingError = new ErrorRecord( new ArgumentException("Argument for parameter cannot be null or whitespace."), - "EmptyOrWhitespaceParameterKey", + "EmptyOrWhitespaceParameterKey", ErrorCategory.InvalidArgument, this); } @@ -55,7 +55,7 @@ public void SetProperty(string propertyName, string propertyValue, out ErrorReco { ParameterParsingError = new ErrorRecord( new ArgumentException("Argument for Version parameter is not in the proper format."), - "IncorrectVersionFormat", + "IncorrectVersionFormat", ErrorCategory.InvalidArgument, this); } @@ -109,7 +109,7 @@ public void SetProperty(string propertyName, string propertyValue, out ErrorReco default: ParameterParsingError = new ErrorRecord( new ArgumentException($"The parameter '{propertyName}' provided is not a recognized or valid parameter. Allowed values include: Name, Version, Repository, AcceptLicense, Prerelease, Scope, Quiet, Reinstall, TrustRepository, NoClobber, and SkipDependencyCheck."), - "IncorrectParameterError", + "IncorrectParameterError", ErrorCategory.InvalidArgument, this); break; diff --git a/src/code/LocalServerApiCalls.cs b/src/code/LocalServerApiCalls.cs index 324db1081..1744c2b0e 100644 --- a/src/code/LocalServerApiCalls.cs +++ b/src/code/LocalServerApiCalls.cs @@ -29,7 +29,7 @@ internal class LocalServerAPICalls : ServerApiCall #region Constructor - public LocalServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential) : base (repository, networkCredential) + public LocalServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential) : base(repository, networkCredential) { this.Repository = repository; _cmdletPassedIn = cmdletPassedIn; @@ -64,9 +64,9 @@ public override FindResults FindTags(string[] tags, bool includePrerelease, Reso if (tagFindResults.IsFindResultsEmpty()) { errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package(s) with Tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), - "FindTagsPackageNotFound", - ErrorCategory.ObjectNotFound, + new ResourceNotFoundException($"Package(s) with Tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), + "FindTagsPackageNotFound", + ErrorCategory.ObjectNotFound, this); } @@ -85,9 +85,9 @@ public override FindResults FindCommandOrDscResource(string[] tags, bool include { string paramName = isSearchingForCommands ? "Command Name(s)" : "DSCResource Name(s)"; errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package(s) with {paramName} '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), - "FindCmdOrDSCNamesPackageNotFound", - ErrorCategory.ObjectNotFound, + new ResourceNotFoundException($"Package(s) with {paramName} '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), + "FindCmdOrDSCNamesPackageNotFound", + ErrorCategory.ObjectNotFound, this); } @@ -173,7 +173,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange // Versions are present in pkgVersionsList in asc order, wherease we need it in desc so we traverse it in reverse. NuGetVersion satisfyingVersion = pkgVersionsList[i]; - string packagePath = (string) pkgVersionsFound[satisfyingVersion]; + string packagePath = (string)pkgVersionsFound[satisfyingVersion]; Hashtable pkgMetadata = GetMetadataFromNupkg(packageName: actualPkgName, packagePath: packagePath, requiredTags: Utils.EmptyStrArray, errRecord: out errRecord); if (errRecord != null || pkgMetadata.Count == 0) @@ -294,9 +294,9 @@ private FindResults FindNameHelper(string packageName, string[] tags, bool inclu { // means no package was found with this name errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package with name {packageName} could not be found in repository '{Repository.Name}'."), - "PackageNotFound", - ErrorCategory.ResourceUnavailable, + new ResourceNotFoundException($"Package with name {packageName} could not be found in repository '{Repository.Name}'."), + "PackageNotFound", + ErrorCategory.ResourceUnavailable, this); return findResponse; @@ -312,13 +312,13 @@ private FindResults FindNameHelper(string packageName, string[] tags, bool inclu if (pkgMetadata.Count == 0) { errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package with name '{packageName}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), - "PackageNotFound", - ErrorCategory.ResourceUnavailable, + new ResourceNotFoundException($"Package with name '{packageName}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), + "PackageNotFound", + ErrorCategory.ResourceUnavailable, this); } - findResponse = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: new Hashtable[]{pkgMetadata}, responseType: _localServerFindResponseType); + findResponse = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: new Hashtable[] { pkgMetadata }, responseType: _localServerFindResponseType); return findResponse; } @@ -336,7 +336,7 @@ private FindResults FindNameGlobbingHelper(string packageName, string[] tags, bo Hashtable pkgVersionsFound = GetMatchingFilesGivenNamePattern(packageNameWithWildcard: packageName, includePrerelease: includePrerelease); List pkgNamesList = pkgVersionsFound.Keys.Cast().ToList(); - foreach(string pkgFound in pkgNamesList) + foreach (string pkgFound in pkgNamesList) { Hashtable pkgInfo = pkgVersionsFound[pkgFound] as Hashtable; string pkgPath = pkgInfo["path"] as string; @@ -369,10 +369,10 @@ private FindResults FindVersionHelper(string packageName, string version, string { errRecord = new ErrorRecord( new InvalidOperationException($"Version {version} could not be parsed into a valid NuGetVersion"), - "FindVersionFailure", - ErrorCategory.InvalidData, + "FindVersionFailure", + ErrorCategory.InvalidData, this); - + return findResponse; } @@ -412,9 +412,9 @@ private FindResults FindVersionHelper(string packageName, string version, string { // means no package was found with this name, version (and possibly tags). errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package with name '{packageName}', version '{version}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), - "PackageNotFound", - ErrorCategory.ResourceUnavailable, + new ResourceNotFoundException($"Package with name '{packageName}', version '{version}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), + "PackageNotFound", + ErrorCategory.ResourceUnavailable, this); return findResponse; @@ -430,13 +430,13 @@ private FindResults FindVersionHelper(string packageName, string version, string if (pkgMetadata.Count == 0) { errRecord = new ErrorRecord( - new ResourceNotFoundException($"Package with name '{packageName}', and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), - "PackageNotFound", - ErrorCategory.InvalidResult, + new ResourceNotFoundException($"Package with name '{packageName}', and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."), + "PackageNotFound", + ErrorCategory.InvalidResult, this); } - findResponse = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: new Hashtable[]{pkgMetadata}, responseType: _localServerFindResponseType); + findResponse = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: new Hashtable[] { pkgMetadata }, responseType: _localServerFindResponseType); return findResponse; } @@ -453,7 +453,7 @@ private FindResults FindTagsHelper(string[] tags, bool includePrerelease, out Er Hashtable pkgVersionsFound = GetMatchingFilesGivenNamePattern(packageNameWithWildcard: String.Empty, includePrerelease: includePrerelease); List pkgNamesList = pkgVersionsFound.Keys.Cast().ToList(); - foreach(string pkgFound in pkgNamesList) + foreach (string pkgFound in pkgNamesList) { Hashtable pkgInfo = pkgVersionsFound[pkgFound] as Hashtable; NuGetVersion pkgVersion = pkgInfo["version"] as NuGetVersion; @@ -673,11 +673,11 @@ private Hashtable GetMetadataFromNupkg(string packageName, string packagePath, s if (!Utils.TryReadManifestFile(psd1FilePath, out pkgMetadata, out Exception readManifestError)) { errRecord = new ErrorRecord( - readManifestError, - "GetMetadataFromNupkgFailure", - ErrorCategory.ParserError, + readManifestError, + "GetMetadataFromNupkgFailure", + ErrorCategory.ParserError, this); - + return pkgMetadata; } @@ -699,9 +699,9 @@ private Hashtable GetMetadataFromNupkg(string packageName, string packagePath, s if (!PSScriptFileInfo.TryTestPSScriptFileInfo(ps1FilePath, out PSScriptFileInfo parsedScript, out ErrorRecord[] errors, out string[] verboseMsgs)) { errRecord = new ErrorRecord( - new InvalidDataException($"PSScriptFile could not be read properly"), - "GetMetadataFromNupkgFailure", - ErrorCategory.ParserError, + new InvalidDataException($"PSScriptFile could not be read properly"), + "GetMetadataFromNupkgFailure", + ErrorCategory.ParserError, this); return pkgMetadata; @@ -724,17 +724,17 @@ private Hashtable GetMetadataFromNupkg(string packageName, string packagePath, s pkgMetadata.Add(_fileTypeKey, Utils.MetadataFileType.Nuspec); string nuspecTags = pkgMetadata["tags"] as string; - string[] nuspecTagsArray = nuspecTags.Split(new char[]{' '}); + string[] nuspecTagsArray = nuspecTags.Split(new char[] { ' ' }); pkgTags.AddRange(nuspecTagsArray); } else { errRecord = new ErrorRecord( new InvalidDataException($".nupkg package must contain either .psd1, .ps1, or .nuspec file and none were found"), - "GetMetadataFromNupkgFailure", - ErrorCategory.InvalidData, + "GetMetadataFromNupkgFailure", + ErrorCategory.InvalidData, this); - + return pkgMetadata; } @@ -747,11 +747,11 @@ private Hashtable GetMetadataFromNupkg(string packageName, string packagePath, s } catch (Exception e) { - errRecord = new ErrorRecord( - new InvalidOperationException($"Temporary folder for installation could not be created or set due to: {e.Message}"), - "GetMetadataFromNupkgFailure", - ErrorCategory.InvalidOperation, - this); + errRecord = new ErrorRecord( + new InvalidOperationException($"Temporary folder for installation could not be created or set due to: {e.Message}"), + "GetMetadataFromNupkgFailure", + ErrorCategory.InvalidOperation, + this); } finally { @@ -892,18 +892,18 @@ private NuGetVersion GetInfoFromFileName(string packageFullName, string packageN // packageFullName will look like package.1.0.0.nupkg errRecord = null; - string[] packageWithoutName = packageFullName.ToLower().Split(new string[]{ $"{packageName.ToLower()}." }, StringSplitOptions.RemoveEmptyEntries); + string[] packageWithoutName = packageFullName.ToLower().Split(new string[] { $"{packageName.ToLower()}." }, StringSplitOptions.RemoveEmptyEntries); string packageVersionAndExtension = packageWithoutName[0]; - string[] originalFileNameParts = packageFullName.ToLower().Split(new string[]{ $".{packageVersionAndExtension.ToLower()}" }, StringSplitOptions.RemoveEmptyEntries); + string[] originalFileNameParts = packageFullName.ToLower().Split(new string[] { $".{packageVersionAndExtension.ToLower()}" }, StringSplitOptions.RemoveEmptyEntries); actualName = String.IsNullOrEmpty(originalFileNameParts[0]) ? packageName : originalFileNameParts[0]; int extensionDot = packageVersionAndExtension.LastIndexOf('.'); string version = packageVersionAndExtension.Substring(0, extensionDot); if (!NuGetVersion.TryParse(version, out NuGetVersion nugetVersion)) { errRecord = new ErrorRecord( - new ArgumentException($"Could not parse version {version} from file {packageFullName}"), - "GetInfoFromFileNameFilaure", - ErrorCategory.ParserError, + new ArgumentException($"Could not parse version {version} from file {packageFullName}"), + "GetInfoFromFileNameFilaure", + ErrorCategory.ParserError, this); return null; @@ -920,13 +920,14 @@ private XmlDocument LoadXmlDocument(string filePath, out ErrorRecord errRecord) errRecord = null; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; - try { doc.Load(filePath); } + try + { doc.Load(filePath); } catch (Exception e) { errRecord = new ErrorRecord( - exception: e, - "LoadXmlDocumentFailure", - ErrorCategory.ReadError, + exception: e, + "LoadXmlDocumentFailure", + ErrorCategory.ReadError, this); } @@ -968,11 +969,11 @@ private Hashtable GetHashtableForNuspec(string filePath, out ErrorRecord errReco try { XmlNodeList elemList = nuspecXmlDocument.GetElementsByTagName("metadata"); - for(int i = 0; i < elemList.Count; i++) + for (int i = 0; i < elemList.Count; i++) { XmlNode metadataInnerXml = elemList[i]; - for(int j= 0; j cmdDSCTags = new List(); - for (int i=0; i - - - - - - + + + + + + + + - - - - + + diff --git a/src/code/ModuleInitAndCleanup.cs b/src/code/ModuleInitAndCleanup.cs index 28e83f284..cda78cbfd 100644 --- a/src/code/ModuleInitAndCleanup.cs +++ b/src/code/ModuleInitAndCleanup.cs @@ -104,7 +104,7 @@ private AssemblyLoadContextProxy(Type alc, string loadContextName) internal Assembly LoadFromAssemblyPath(string assemblyPath) { - return (Assembly) _loadFromAssemblyPath.Invoke(_customContext, new[] { assemblyPath }); + return (Assembly)_loadFromAssemblyPath.Invoke(_customContext, new[] { assemblyPath }); } internal static AssemblyLoadContextProxy CreateLoadContext(string name) diff --git a/src/code/NuGetServerAPICalls.cs b/src/code/NuGetServerAPICalls.cs index 2ecabd001..9d22aa942 100644 --- a/src/code/NuGetServerAPICalls.cs +++ b/src/code/NuGetServerAPICalls.cs @@ -23,14 +23,14 @@ internal class NuGetServerAPICalls : ServerApiCall public override PSRepositoryInfo Repository { get; set; } private readonly PSCmdlet _cmdletPassedIn; private HttpClient _sessionClient { get; set; } - private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{}; + private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { }; public FindResponseType FindResponseType = FindResponseType.ResponseString; #endregion #region Constructor - public NuGetServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base (repository, networkCredential) + public NuGetServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base(repository, networkCredential) { this.Repository = repository; _cmdletPassedIn = cmdletPassedIn; @@ -180,7 +180,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, var requestUrl = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}"; string response = HttpRequestCall(requestUrl, out errRecord); - return new FindResults(stringResponse: new string[]{ response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType); + return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: FindResponseType); } /// @@ -195,12 +195,12 @@ public override FindResults FindNameWithTag(string packageName, string[] tags, b // This should return the latest stable version or the latest prerelease version (respectively) // https://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'&$filter=IsLatestVersion and substringof('PSModule', Tags) eq true - + var queryBuilder = new NuGetV2QueryBuilder(new Dictionary{ { "id", $"'{packageName}'" }, }); var filterBuilder = queryBuilder.FilterBuilder; - + // We need to explicitly add 'Id eq ' whenever $filter is used, otherwise arbitrary results are returned. filterBuilder.AddCriterion($"Id eq '{packageName}'"); @@ -516,7 +516,7 @@ private HttpContent HttpRequestCallForContent(string requestUrl, out ErrorRecord errRecord = new ErrorRecord( exception: e, "HttpRequestFailure", - ErrorCategory.ConnectionError , + ErrorCategory.ConnectionError, this); } catch (ArgumentNullException e) @@ -564,13 +564,16 @@ private string FindAllFromEndPoint(bool includePrerelease, int skip, out ErrorRe var filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } - + var requestUrl = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}"; return HttpRequestCall(requestUrl, out errRecord); @@ -592,10 +595,13 @@ private string FindTagFromEndpoint(string[] tags, bool includePrerelease, int sk var filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } @@ -627,15 +633,18 @@ private string FindNameGlobbing(string packageName, bool includePrerelease, int var filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (names.Length == 0) { @@ -707,14 +716,17 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, bool i var filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); queryBuilder.AdditionalParameters["includePrerelease"] = "true"; - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (names.Length == 0) { @@ -840,7 +852,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange filterBuilder.AddCriterion(maxPart); } - if (!includePrerelease) { + if (!includePrerelease) + { filterBuilder.AddCriterion("IsPrerelease eq false"); } diff --git a/src/code/NuGetServerResponseUtil.cs b/src/code/NuGetServerResponseUtil.cs index 3a553e4ed..8e93c9c2d 100644 --- a/src/code/NuGetServerResponseUtil.cs +++ b/src/code/NuGetServerResponseUtil.cs @@ -69,18 +69,19 @@ public override IEnumerable ConvertToPSResourceResult(FindResu #region NuGet.Server Specific Methods - public XmlNode[] ConvertResponseToXML(string httpResponse) { + public XmlNode[] ConvertResponseToXML(string httpResponse) + { //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml(httpResponse); XmlNodeList elemList = doc.GetElementsByTagName("m:properties"); - - XmlNode[] nodes = new XmlNode[elemList.Count]; - for (int i = 0; i < elemList.Count; i++) + + XmlNode[] nodes = new XmlNode[elemList.Count]; + for (int i = 0; i < elemList.Count; i++) { - nodes[i] = elemList[i]; + nodes[i] = elemList[i]; } return nodes; diff --git a/src/code/PSCredentialInfo.cs b/src/code/PSCredentialInfo.cs index 929191f59..d3f7c8fed 100644 --- a/src/code/PSCredentialInfo.cs +++ b/src/code/PSCredentialInfo.cs @@ -31,29 +31,29 @@ public PSCredentialInfo(string vaultName, string secretName, PSCredential creden Credential = credential; } - /// + /// /// Initializes a new instance of the PSCredentialInfo class with /// containing vaultName and secretName of type string, and /// (optionally) credential of type PSCredential from a Hashtable. /// /// public PSCredentialInfo(Hashtable hashtable) - { - if (!(hashtable.ContainsKey("VaultName") && (hashtable.ContainsKey("SecretName") || hashtable.ContainsKey("Name")))) + { + if (!(hashtable.ContainsKey("VaultName") && (hashtable.ContainsKey("SecretName") || hashtable.ContainsKey("Name")))) { - throw new ArgumentException("Credential Information must contain the keys 'VaultName' and 'SecretName'!"); - } + throw new ArgumentException("Credential Information must contain the keys 'VaultName' and 'SecretName'!"); + } VaultName = hashtable["VaultName"] as string; - if (hashtable.ContainsKey("SecretName")) - SecretName = hashtable["SecretName"] as string; - else - SecretName = hashtable["Name"] as string; + if (hashtable.ContainsKey("SecretName")) + SecretName = hashtable["SecretName"] as string; + else + SecretName = hashtable["Name"] as string; - if (hashtable.ContainsKey("Credential") && hashtable["Credential"] is PSCredential psCred) - { - Credential = psCred; - } - } + if (hashtable.ContainsKey("Credential") && hashtable["Credential"] is PSCredential psCred) + { + Credential = psCred; + } + } /// /// Initializes a new instance of the PSCredentialInfo class with @@ -68,11 +68,11 @@ public PSCredentialInfo(PSObject psObject) throw new ArgumentNullException(nameof(psObject)); } - VaultName = (string) psObject.Properties[PSCredentialInfo.VaultNameAttribute]?.Value; - SecretName = (string) psObject.Properties[PSCredentialInfo.SecretNameAttribute]?.Value; - if (String.IsNullOrEmpty(SecretName)) - SecretName = (string) psObject.Properties["Name"]?.Value; - + VaultName = (string)psObject.Properties[PSCredentialInfo.VaultNameAttribute]?.Value; + SecretName = (string)psObject.Properties[PSCredentialInfo.SecretNameAttribute]?.Value; + if (String.IsNullOrEmpty(SecretName)) + SecretName = (string)psObject.Properties["Name"]?.Value; + var credentialAttr = psObject.Properties[PSCredentialInfo.CredentialAttribute]?.Value; if (credentialAttr is string credStr) { @@ -96,7 +96,8 @@ public PSCredentialInfo(PSObject psObject) /// /// the Name of the SecretManagement Vault /// - public string VaultName { + public string VaultName + { get { return _vaultName; @@ -117,7 +118,8 @@ private set /// /// the Name of the Secret /// - public string SecretName { + public string SecretName + { get { return _secretName; diff --git a/src/code/PSGetException.cs b/src/code/PSGetException.cs index 8385d1cdf..922dea184 100644 --- a/src/code/PSGetException.cs +++ b/src/code/PSGetException.cs @@ -24,7 +24,7 @@ public UnauthorizedException(string message, Exception innerException = null) public class JsonParsingException : Exception { public JsonParsingException(string message, Exception innerException = null) - : base (message) + : base(message) { } } @@ -48,15 +48,15 @@ public ConvertToPSResourceException(string message, Exception innerException = n public class InvalidOrEmptyResponse : Exception { public InvalidOrEmptyResponse(string message, Exception innerException = null) - : base (message) - { + : base(message) + { } } public class LocalResourceEmpty : Exception { public LocalResourceEmpty(string message, Exception innerException = null) - : base (message) + : base(message) { } } @@ -64,7 +64,7 @@ public LocalResourceEmpty(string message, Exception innerException = null) public class LocalResourceNotFoundException : Exception { public LocalResourceNotFoundException(string message, Exception innerException = null) - : base (message) + : base(message) { } } diff --git a/src/code/PSRepositoryInfo.cs b/src/code/PSRepositoryInfo.cs index 07dd06762..eda4feab4 100644 --- a/src/code/PSRepositoryInfo.cs +++ b/src/code/PSRepositoryInfo.cs @@ -104,7 +104,7 @@ public enum RepositoryProviderType internal bool IsMARRepository() { - return (ApiVersion == APIVersion.ContainerRegistry && Uri.Host.StartsWith("mcr.microsoft") ); + return (ApiVersion == APIVersion.ContainerRegistry && Uri.Host.StartsWith("mcr.microsoft")); } #endregion diff --git a/src/code/PSResourceInfo.cs b/src/code/PSResourceInfo.cs index 6ddfe6e57..a79ebef21 100644 --- a/src/code/PSResourceInfo.cs +++ b/src/code/PSResourceInfo.cs @@ -985,7 +985,7 @@ public static bool TryConvertFromContainerRegistryJson( } if (rootDom.TryGetProperty("CompanyName", out JsonElement companyNameElement)) - { + { metadata["CompanyName"] = companyNameElement.ToString(); } else diff --git a/src/code/PSScriptContents.cs b/src/code/PSScriptContents.cs index ef56f0174..9071ea9a6 100644 --- a/src/code/PSScriptContents.cs +++ b/src/code/PSScriptContents.cs @@ -46,7 +46,7 @@ public PSScriptContents(string[] endOfFileContents) /// This constructor creates a PSScriptContents instance with default values for its properties. /// The calling method, like PSScriptContents.ParseContent() could then populate the properties. /// - internal PSScriptContents() {} + internal PSScriptContents() { } #endregion diff --git a/src/code/PSScriptFileInfo.cs b/src/code/PSScriptFileInfo.cs index d71c34e78..d491a3fd0 100644 --- a/src/code/PSScriptFileInfo.cs +++ b/src/code/PSScriptFileInfo.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.PSResourceGet.UtilClasses public sealed class PSScriptFileInfo { #region Properties - + public PSScriptMetadata ScriptMetadataComment { get; set; } public PSScriptHelp ScriptHelpComment { get; set; } @@ -109,7 +109,7 @@ internal static bool TryParseScriptFileContents( ref string[] remainingFileContent, out ErrorRecord error) { - error= null; + error = null; psScriptInfoCommentContent = new List(); helpInfoCommentContent = new List(); @@ -126,7 +126,7 @@ internal static bool TryParseScriptFileContents( while (i < fileContents.Length) { string line = fileContents[i]; - + if (line.Trim().StartsWith("<#PSScriptInfo")) { int j = i + 1; // start at the next line @@ -142,7 +142,7 @@ internal static bool TryParseScriptFileContents( i = j + 1; break; } - + j++; } @@ -150,8 +150,8 @@ internal static bool TryParseScriptFileContents( { error = new ErrorRecord( new InvalidOperationException($"Could not parse '{scriptFileInfoPath}' as a PowerShell script file due to missing the closing '#>' for <#PSScriptInfo comment block"), - "MissingEndBracketToPSScriptInfoParseError", - ErrorCategory.ParserError, + "MissingEndBracketToPSScriptInfoParseError", + ErrorCategory.ParserError, null); return false; @@ -182,7 +182,7 @@ internal static bool TryParseScriptFileContents( { error = new ErrorRecord( new InvalidOperationException($"Could not parse '{scriptFileInfoPath}' as a PowerShell script file due to missing the closing '#>' for HelpInfo comment block"), - "MissingEndBracketToHelpInfoCommentParseError", + "MissingEndBracketToHelpInfoCommentParseError", ErrorCategory.ParserError, null); @@ -218,8 +218,8 @@ internal static bool TryParseScriptFileContents( // check for file not containing '<#PSScriptInfo ... #>' comment error = new ErrorRecord( new InvalidOperationException($"Could not parse '{scriptFileInfoPath}' as a PowerShell script due to it missing '<#PSScriptInfo #> block"), - "MissingEndBracketToHelpInfoCommentParseError", - ErrorCategory.ParserError, + "MissingEndBracketToHelpInfoCommentParseError", + ErrorCategory.ParserError, null); return false; @@ -230,8 +230,8 @@ internal static bool TryParseScriptFileContents( // check for file not containing HelpInfo comment error = new ErrorRecord( new InvalidOperationException($"Could not parse '{scriptFileInfoPath}' as a PowerShell script due to it missing HelpInfo comment block"), - "missingHelpInfoCommentError", - ErrorCategory.ParserError, + "missingHelpInfoCommentError", + ErrorCategory.ParserError, null); return false; @@ -323,7 +323,7 @@ internal static bool TryTestPSScriptFileInfo( remainingFileContent: ref remainingFileContent, out ErrorRecord parseError)) { - errors = new ErrorRecord[]{parseError}; + errors = new ErrorRecord[] { parseError }; return false; } @@ -357,7 +357,7 @@ internal static bool TryTestPSScriptFileInfo( { errors = new ErrorRecord[]{ new ErrorRecord( new ArgumentException($"PSScriptFileInfo object could not be created from passed in file due to {e.Message}"), - "PSScriptFileInfoObjectNotCreatedFromFileError", + "PSScriptFileInfoObjectNotCreatedFromFileError", ErrorCategory.ParserError, null) }; @@ -511,7 +511,7 @@ internal Hashtable ToHashtable() Hashtable scriptHashtable = new Hashtable(StringComparer.OrdinalIgnoreCase); Hashtable metadataObjectHashtable = ScriptMetadataComment.ToHashtable(); - foreach(string key in metadataObjectHashtable.Keys) + foreach (string key in metadataObjectHashtable.Keys) { if (!scriptHashtable.ContainsKey(key)) { diff --git a/src/code/PSScriptHelp.cs b/src/code/PSScriptHelp.cs index 7bbf2f70e..c27889a2b 100644 --- a/src/code/PSScriptHelp.cs +++ b/src/code/PSScriptHelp.cs @@ -32,7 +32,7 @@ public sealed class PSScriptHelp /// /// This constructor takes a value for description and creates a new PSScriptHelp instance. /// - public PSScriptHelp (string description) + public PSScriptHelp(string description) { Description = description; } @@ -41,12 +41,12 @@ public PSScriptHelp (string description) /// This constructor is called by internal cmdlet methods and creates a PSScriptHelp with default values /// for the parameters. Calling a method like PSScriptHelp.ParseConentIntoObj() would then populate those properties. /// - internal PSScriptHelp() {} + internal PSScriptHelp() { } #endregion #region Internal Methods - + /// /// Parses HelpInfo metadata out of the HelpInfo comment lines found while reading the file /// and populates PSScriptHelp properties from that metadata. @@ -54,7 +54,7 @@ internal PSScriptHelp() {} internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord error) { error = null; - + // Parse content into a hashtable. Hashtable parsedHelpMetadata = ParseHelpContentHelper(commentLines); @@ -63,13 +63,13 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord error) error = validationError; return false; } - + // Populate object. - List descriptionValue = (List) parsedHelpMetadata["DESCRIPTION"]; + List descriptionValue = (List)parsedHelpMetadata["DESCRIPTION"]; Description = String.Join(Environment.NewLine, descriptionValue); if (parsedHelpMetadata.ContainsKey("HELPCONTENT")) { - HelpContent = (List) parsedHelpMetadata["HELPCONTENT"]; + HelpContent = (List)parsedHelpMetadata["HELPCONTENT"]; } return true; @@ -103,7 +103,7 @@ value continued List descriptionValue = new List(); bool parsingDescription = false; - for(int i = 0; i < commentLines.Length; i++) + for (int i = 0; i < commentLines.Length; i++) { string line = commentLines[i]; if (line.Trim().StartsWith(".DESCRIPTION", StringComparison.OrdinalIgnoreCase)) @@ -137,7 +137,7 @@ value continued return parsedHelpMetadata; } - + /// /// Valides parsed help info content from the hashtable to ensure required help metadata (Description) is present /// and does not contain empty values. @@ -147,23 +147,23 @@ internal bool ValidateParsedContent(Hashtable parsedHelpMetadata, out ErrorRecor error = null; if (!parsedHelpMetadata.ContainsKey("DESCRIPTION")) { - error = new ErrorRecord( - new ArgumentException( "PSScript file must contain value for Description. Ensure value for Description is passed in and try again."), - "PSScriptInfoMissingDescription", - ErrorCategory.InvalidArgument, + error = new ErrorRecord( + new ArgumentException("PSScript file must contain value for Description. Ensure value for Description is passed in and try again."), + "PSScriptInfoMissingDescription", + ErrorCategory.InvalidArgument, null); return false; } - List descriptionValue = (List) parsedHelpMetadata["DESCRIPTION"]; + List descriptionValue = (List)parsedHelpMetadata["DESCRIPTION"]; string descriptionString = String.Join("", descriptionValue); if (descriptionValue.Count == 0 || (String.IsNullOrEmpty(descriptionString)) || String.IsNullOrWhiteSpace(descriptionString)) { error = new ErrorRecord( - new ArgumentException("PSScript file value for Description cannot be null, empty or whitespace. Ensure value for Description meets these conditions and try again."), - "PSScriptInfoMissingDescription", - ErrorCategory.InvalidArgument, + new ArgumentException("PSScript file value for Description cannot be null, empty or whitespace. Ensure value for Description meets these conditions and try again."), + "PSScriptInfoMissingDescription", + ErrorCategory.InvalidArgument, null); return false; @@ -172,12 +172,12 @@ internal bool ValidateParsedContent(Hashtable parsedHelpMetadata, out ErrorRecor if (StringContainsComment(descriptionString)) { error = new ErrorRecord( - new ArgumentException("PSScript file's value for Description cannot contain '<#' or '#>'. Pass in a valid value for Description and try again."), - "DescriptionContainsComment", - ErrorCategory.InvalidArgument, + new ArgumentException("PSScript file's value for Description cannot contain '<#' or '#>'. Pass in a valid value for Description and try again."), + "DescriptionContainsComment", + ErrorCategory.InvalidArgument, null); - return false; + return false; } return true; @@ -193,9 +193,9 @@ internal bool ValidateContent(out ErrorRecord error) if (String.IsNullOrEmpty(Description)) { error = new ErrorRecord( - new ArgumentException("PSScript file must contain value for Description. Ensure value for Description is passed in and try again."), - "PSScriptInfoMissingDescription", - ErrorCategory.InvalidArgument, + new ArgumentException("PSScript file must contain value for Description. Ensure value for Description is passed in and try again."), + "PSScriptInfoMissingDescription", + ErrorCategory.InvalidArgument, null); return false; @@ -203,13 +203,13 @@ internal bool ValidateContent(out ErrorRecord error) if (StringContainsComment(Description)) { - error = new ErrorRecord( - new ArgumentException("PSScript file's value for Description cannot contain '<#' or '#>'. Pass in a valid value for Description and try again."), - "DescriptionContainsComment", - ErrorCategory.InvalidArgument, + error = new ErrorRecord( + new ArgumentException("PSScript file's value for Description cannot contain '<#' or '#>'. Pass in a valid value for Description and try again."), + "DescriptionContainsComment", + ErrorCategory.InvalidArgument, null); - return false; + return false; } return true; @@ -231,7 +231,7 @@ internal string[] EmitContent() { psHelpInfoLines.AddRange(HelpContent); } - + psHelpInfoLines.Add("#>"); return psHelpInfoLines.ToArray(); @@ -249,9 +249,9 @@ internal bool UpdateContent(string description, out ErrorRecord error) if (String.Equals(description.Trim(), String.Empty)) { error = new ErrorRecord( - new ArgumentException("Description value can't be updated to whitespace as this would invalidate the script."), - "descriptionUpdateValueIsWhitespaceError", - ErrorCategory.InvalidArgument, + new ArgumentException("Description value can't be updated to whitespace as this would invalidate the script."), + "descriptionUpdateValueIsWhitespaceError", + ErrorCategory.InvalidArgument, null); return false; @@ -260,9 +260,9 @@ internal bool UpdateContent(string description, out ErrorRecord error) if (StringContainsComment(description)) { error = new ErrorRecord( - new ArgumentException("Description value can't be updated to value containing comment '<#' or '#>' as this would invalidate the script."), - "descriptionUpdateValueContainsCommentError", - ErrorCategory.InvalidArgument, + new ArgumentException("Description value can't be updated to value containing comment '<#' or '#>' as this would invalidate the script."), + "descriptionUpdateValueContainsCommentError", + ErrorCategory.InvalidArgument, null); return false; diff --git a/src/code/PSScriptMetadata.cs b/src/code/PSScriptMetadata.cs index bd6cf1e94..803d789b4 100644 --- a/src/code/PSScriptMetadata.cs +++ b/src/code/PSScriptMetadata.cs @@ -114,7 +114,7 @@ public PSScriptMetadata( author = Environment.UserName; } - Version = !String.IsNullOrEmpty(version) ? new NuGetVersion (version) : new NuGetVersion("1.0.0.0"); + Version = !String.IsNullOrEmpty(version) ? new NuGetVersion(version) : new NuGetVersion("1.0.0.0"); Guid = (guid == null || guid == Guid.Empty) ? Guid.NewGuid() : guid; Author = !String.IsNullOrEmpty(author) ? author : Environment.UserName; CompanyName = companyName; @@ -134,7 +134,7 @@ public PSScriptMetadata( /// This constructor is called by internal cmdlet methods and creates a PSScriptFileInfo with default values /// for the parameters. Calling a method like PSScriptMetadata.ParseConentIntoObj() would then populate those properties. /// - internal PSScriptMetadata() {} + internal PSScriptMetadata() { } #endregion @@ -160,9 +160,9 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error if (parsedMetadata.Count == 0) { errors = new ErrorRecord[]{ new ErrorRecord( - new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block contains no metadata"), - "psScriptInfoBlockMissingMetadataError", - ErrorCategory.ParserError, + new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block contains no metadata"), + "psScriptInfoBlockMissingMetadataError", + ErrorCategory.ParserError, null) }; return false; @@ -175,53 +175,54 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error } // now populate the object instance - string[] delimeter = new string[]{" ", ","}; + string[] delimeter = new string[] { " ", "," }; Uri parsedLicenseUri = null; - if (!String.IsNullOrEmpty((string) parsedMetadata["LICENSEURI"])) + if (!String.IsNullOrEmpty((string)parsedMetadata["LICENSEURI"])) { - if (!Uri.TryCreate((string) parsedMetadata["LICENSEURI"], UriKind.Absolute, out parsedLicenseUri)) + if (!Uri.TryCreate((string)parsedMetadata["LICENSEURI"], UriKind.Absolute, out parsedLicenseUri)) { - msgsList.Add($"LicenseUri property {(string) parsedMetadata["LICENSEURI"]} could not be created as a Uri"); + msgsList.Add($"LicenseUri property {(string)parsedMetadata["LICENSEURI"]} could not be created as a Uri"); } } Uri parsedProjectUri = null; - if (!String.IsNullOrEmpty((string) parsedMetadata["PROJECTURI"])) + if (!String.IsNullOrEmpty((string)parsedMetadata["PROJECTURI"])) { - if (!Uri.TryCreate((string) parsedMetadata["PROJECTURI"], UriKind.Absolute, out parsedProjectUri)) + if (!Uri.TryCreate((string)parsedMetadata["PROJECTURI"], UriKind.Absolute, out parsedProjectUri)) { - msgsList.Add($"ProjectUri property {(string) parsedMetadata["PROJECTURI"]} could not be created as Uri"); + msgsList.Add($"ProjectUri property {(string)parsedMetadata["PROJECTURI"]} could not be created as Uri"); } } Uri parsedIconUri = null; - if (!String.IsNullOrEmpty((string) parsedMetadata["ICONURI"])) + if (!String.IsNullOrEmpty((string)parsedMetadata["ICONURI"])) { - if (!Uri.TryCreate((string) parsedMetadata["ICONURI"], UriKind.Absolute, out parsedIconUri)) + if (!Uri.TryCreate((string)parsedMetadata["ICONURI"], UriKind.Absolute, out parsedIconUri)) { - msgsList.Add($"IconUri property {(string) parsedMetadata["ICONURI"]} could not be created as Uri"); + msgsList.Add($"IconUri property {(string)parsedMetadata["ICONURI"]} could not be created as Uri"); } } // now populate PSScriptMetadata object properties with parsed metadata - Author = (string) parsedMetadata["AUTHOR"]; - Version = new NuGetVersion((string) parsedMetadata["VERSION"]); - Guid = new Guid((string) parsedMetadata["GUID"]); + Author = (string)parsedMetadata["AUTHOR"]; + Version = new NuGetVersion((string)parsedMetadata["VERSION"]); + Guid = new Guid((string)parsedMetadata["GUID"]); - CompanyName = (string) parsedMetadata["COMPANYNAME"] ?? String.Empty; - Copyright = (string) parsedMetadata["COPYRIGHT"] ?? String.Empty; + CompanyName = (string)parsedMetadata["COMPANYNAME"] ?? String.Empty; + Copyright = (string)parsedMetadata["COPYRIGHT"] ?? String.Empty; LicenseUri = parsedLicenseUri; ProjectUri = parsedProjectUri; IconUri = parsedIconUri; - - Tags = Utils.GetStringArrayFromString(delimeter, (string) parsedMetadata["TAGS"]);; - ExternalModuleDependencies = Utils.GetStringArrayFromString(delimeter, (string) parsedMetadata["EXTERNALMODULEDEPENDENCIES"]); - RequiredScripts = Utils.GetStringArrayFromString(delimeter, (string) parsedMetadata["REQUIREDSCRIPTS"]); - ExternalScriptDependencies = Utils.GetStringArrayFromString(delimeter, (string) parsedMetadata["EXTERNALSCRIPTDEPENDENCIES"]); - ReleaseNotes = (string) parsedMetadata["RELEASENOTES"] ?? String.Empty; - PrivateData = (string) parsedMetadata["PRIVATEDATA"] ?? String.Empty; + + Tags = Utils.GetStringArrayFromString(delimeter, (string)parsedMetadata["TAGS"]); + ; + ExternalModuleDependencies = Utils.GetStringArrayFromString(delimeter, (string)parsedMetadata["EXTERNALMODULEDEPENDENCIES"]); + RequiredScripts = Utils.GetStringArrayFromString(delimeter, (string)parsedMetadata["REQUIREDSCRIPTS"]); + ExternalScriptDependencies = Utils.GetStringArrayFromString(delimeter, (string)parsedMetadata["EXTERNALSCRIPTDEPENDENCIES"]); + ReleaseNotes = (string)parsedMetadata["RELEASENOTES"] ?? String.Empty; + PrivateData = (string)parsedMetadata["PRIVATEDATA"] ?? String.Empty; msgs = msgsList.ToArray(); return true; @@ -252,7 +253,7 @@ value continued List errorsList = new List(); Hashtable parsedHelpMetadata = new Hashtable(StringComparer.OrdinalIgnoreCase); - char[] delimeter = new char[]{' ', ','}; + char[] delimeter = new char[] { ' ', ',' }; string keyName = ""; string value = ""; @@ -270,15 +271,15 @@ value continued if (parsedHelpMetadata.ContainsKey(keyName)) { errorsList.Add(new ErrorRecord( - new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block metadata cannot contain duplicate key i.e .KEY"), - "psScriptInfoDuplicateKeyError", - ErrorCategory.ParserError, + new InvalidOperationException("PowerShell script '<#PSScriptInfo .. #>' comment block metadata cannot contain duplicate key i.e .KEY"), + "psScriptInfoDuplicateKeyError", + ErrorCategory.ParserError, null)); continue; } - parsedHelpMetadata.Add(keyName, value); + parsedHelpMetadata.Add(keyName, value); } // setting count to 2 will get 1st separated string (key) into part[0] and the rest (value) into part[1] if any @@ -323,30 +324,30 @@ internal bool ValidateParsedContent(Hashtable parsedMetadata, out ErrorRecord[] { List errorsList = new List(); - if (!parsedMetadata.ContainsKey("VERSION") || String.IsNullOrEmpty((string) parsedMetadata["VERSION"]) || String.Equals(((string) parsedMetadata["VERSION"]).Trim(), String.Empty)) + if (!parsedMetadata.ContainsKey("VERSION") || String.IsNullOrEmpty((string)parsedMetadata["VERSION"]) || String.Equals(((string)parsedMetadata["VERSION"]).Trim(), String.Empty)) { errorsList.Add(new ErrorRecord( - new ArgumentException("PSScript file is missing the required Version property"), - "psScriptMissingVersion", - ErrorCategory.ParserError, + new ArgumentException("PSScript file is missing the required Version property"), + "psScriptMissingVersion", + ErrorCategory.ParserError, null)); } - if (!parsedMetadata.ContainsKey("AUTHOR") || String.IsNullOrEmpty((string) parsedMetadata["AUTHOR"]) || String.Equals(((string) parsedMetadata["AUTHOR"]).Trim(), String.Empty)) + if (!parsedMetadata.ContainsKey("AUTHOR") || String.IsNullOrEmpty((string)parsedMetadata["AUTHOR"]) || String.Equals(((string)parsedMetadata["AUTHOR"]).Trim(), String.Empty)) { errorsList.Add(new ErrorRecord( - new ArgumentException("PSScript file is missing the required Author property"), - "psScriptMissingAuthor", - ErrorCategory.ParserError, + new ArgumentException("PSScript file is missing the required Author property"), + "psScriptMissingAuthor", + ErrorCategory.ParserError, null)); } - if (!parsedMetadata.ContainsKey("GUID") || String.IsNullOrEmpty((string) parsedMetadata["GUID"]) || String.Equals(((string) parsedMetadata["GUID"]).Trim(), String.Empty)) + if (!parsedMetadata.ContainsKey("GUID") || String.IsNullOrEmpty((string)parsedMetadata["GUID"]) || String.Equals(((string)parsedMetadata["GUID"]).Trim(), String.Empty)) { errorsList.Add(new ErrorRecord( - new ArgumentException("PSScript file is missing the required Guid property"), - "psScriptMissingGuid", - ErrorCategory.ParserError, + new ArgumentException("PSScript file is missing the required Guid property"), + "psScriptMissingGuid", + ErrorCategory.ParserError, null)); } @@ -365,9 +366,9 @@ internal bool ValidateContent(out ErrorRecord[] errors) if (Version == null || String.IsNullOrEmpty(Version.ToString())) { errorsList.Add(new ErrorRecord( - new ArgumentException("PSScript file is missing the required Version property"), - "psScriptMissingVersion", - ErrorCategory.ParserError, + new ArgumentException("PSScript file is missing the required Version property"), + "psScriptMissingVersion", + ErrorCategory.ParserError, null)); validPSScriptInfo = false; } @@ -375,9 +376,9 @@ internal bool ValidateContent(out ErrorRecord[] errors) if (String.IsNullOrEmpty(Author)) { errorsList.Add(new ErrorRecord( - new ArgumentException("PSScript file is missing the required Author property"), - "psScriptMissingAuthor", - ErrorCategory.ParserError, + new ArgumentException("PSScript file is missing the required Author property"), + "psScriptMissingAuthor", + ErrorCategory.ParserError, null)); validPSScriptInfo = false; } @@ -386,8 +387,8 @@ internal bool ValidateContent(out ErrorRecord[] errors) { errorsList.Add(new ErrorRecord( new ArgumentException("PSScript file is missing the required Guid property"), - "psScriptMissingGuid", - ErrorCategory.ParserError, + "psScriptMissingGuid", + ErrorCategory.ParserError, null)); validPSScriptInfo = false; } @@ -484,10 +485,10 @@ internal bool UpdateContent( { if (!NuGetVersion.TryParse(version, out NuGetVersion updatedVersion)) { - error = new ErrorRecord( - new ArgumentException("Version provided for update could not be parsed successfully into NuGetVersion"), - "VersionParseIntoNuGetVersion", - ErrorCategory.ParserError, + error = new ErrorRecord( + new ArgumentException("Version provided for update could not be parsed successfully into NuGetVersion"), + "VersionParseIntoNuGetVersion", + ErrorCategory.ParserError, null); return false; @@ -506,32 +507,39 @@ internal bool UpdateContent( Author = author; } - if (!String.IsNullOrEmpty(companyName)){ + if (!String.IsNullOrEmpty(companyName)) + { CompanyName = companyName; } - if (!String.IsNullOrEmpty(copyright)){ + if (!String.IsNullOrEmpty(copyright)) + { Copyright = copyright; } - if (tags != null && tags.Length != 0){ + if (tags != null && tags.Length != 0) + { Tags = tags; } - if (licenseUri != null && !licenseUri.Equals(default(Uri))){ + if (licenseUri != null && !licenseUri.Equals(default(Uri))) + { LicenseUri = licenseUri; } - if (projectUri != null && !projectUri.Equals(default(Uri))){ + if (projectUri != null && !projectUri.Equals(default(Uri))) + { ProjectUri = projectUri; } - if (iconUri != null && !iconUri.Equals(default(Uri))){ + if (iconUri != null && !iconUri.Equals(default(Uri))) + { IconUri = iconUri; } - if (externalModuleDependencies != null && externalModuleDependencies.Length != 0){ - ExternalModuleDependencies = externalModuleDependencies; + if (externalModuleDependencies != null && externalModuleDependencies.Length != 0) + { + ExternalModuleDependencies = externalModuleDependencies; } if (requiredScripts != null && requiredScripts.Length != 0) @@ -539,8 +547,9 @@ internal bool UpdateContent( RequiredScripts = requiredScripts; } - if (externalScriptDependencies != null && externalScriptDependencies.Length != 0){ - ExternalScriptDependencies = externalScriptDependencies; + if (externalScriptDependencies != null && externalScriptDependencies.Length != 0) + { + ExternalScriptDependencies = externalScriptDependencies; } if (!String.IsNullOrEmpty(releaseNotes)) diff --git a/src/code/PSScriptRequires.cs b/src/code/PSScriptRequires.cs index c9d34105c..a6ddecc7f 100644 --- a/src/code/PSScriptRequires.cs +++ b/src/code/PSScriptRequires.cs @@ -40,7 +40,7 @@ public PSScriptRequires(ModuleSpecification[] requiredModules) /// This constructor is called by internal cmdlet methods and creates a PSScriptHelp with default values /// for the parameters. Calling a method like PSScriptRequires.ParseConentIntoObj() would then populate those properties. /// - internal PSScriptRequires() {} + internal PSScriptRequires() { } #endregion @@ -72,15 +72,15 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error requiresComment, out Token[] tokens, out ParseError[] parserErrors); - + if (parserErrors.Length > 0) { foreach (ParseError err in parserErrors) { errorsList.Add(new ErrorRecord( - new InvalidOperationException($"Could not requires comments as valid PowerShell input due to {err.Message}."), - err.ErrorId, - ErrorCategory.ParserError, + new InvalidOperationException($"Could not requires comments as valid PowerShell input due to {err.Message}."), + err.ErrorId, + ErrorCategory.ParserError, null)); } @@ -100,12 +100,12 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error catch (Exception e) { errorsList.Add(new ErrorRecord( - new ArgumentException($"Parsing RequiredModules failed due to {e.Message}"), - "requiredModulesAstParseThrewError", - ErrorCategory.ParserError, + new ArgumentException($"Parsing RequiredModules failed due to {e.Message}"), + "requiredModulesAstParseThrewError", + ErrorCategory.ParserError, null)); errors = errorsList.ToArray(); - + return false; } @@ -125,7 +125,7 @@ internal string[] EmitContent() { psRequiresLines.Add(String.Format("#Requires -Module {0}", moduleSpec.ToString())); } - + psRequiresLines.Add(String.Empty); } @@ -137,7 +137,8 @@ internal string[] EmitContent() /// internal void UpdateContent(ModuleSpecification[] requiredModules) { - if (requiredModules != null && requiredModules.Length != 0){ + if (requiredModules != null && requiredModules.Length != 0) + { RequiredModules = requiredModules; } } diff --git a/src/code/PublishHelper.cs b/src/code/PublishHelper.cs index 4cbfb0f4a..9912c67c4 100644 --- a/src/code/PublishHelper.cs +++ b/src/code/PublishHelper.cs @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets { - internal class PublishHelper + internal class PublishHelper { #region Enums internal enum CallerCmdlet @@ -120,27 +120,27 @@ internal void PackResource() parsedMetadata = new Hashtable(StringComparer.OrdinalIgnoreCase); if (resourceType == ResourceType.Script) + { + if (!PSScriptFileInfo.TryTestPSScriptFileInfo( + scriptFileInfoPath: pathToScriptFileToPublish, + parsedScript: out PSScriptFileInfo scriptToPublish, + out ErrorRecord[] errors, + out string[] _ + )) { - if (!PSScriptFileInfo.TryTestPSScriptFileInfo( - scriptFileInfoPath: pathToScriptFileToPublish, - parsedScript: out PSScriptFileInfo scriptToPublish, - out ErrorRecord[] errors, - out string[] _ - )) + foreach (ErrorRecord error in errors) { - foreach (ErrorRecord error in errors) - { - _cmdletPassedIn.WriteError(error); - } + _cmdletPassedIn.WriteError(error); + } - ScriptError = true; + ScriptError = true; - return; - } + return; + } - parsedMetadata = scriptToPublish.ToHashtable(); + parsedMetadata = scriptToPublish.ToHashtable(); - _pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToScriptFileToPublish); + _pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToScriptFileToPublish); } else { @@ -320,7 +320,7 @@ out string[] _ } finally { - if(_callerCmdlet == CallerCmdlet.CompressPSResource) + if (_callerCmdlet == CallerCmdlet.CompressPSResource) { _cmdletPassedIn.WriteVerbose(string.Format("Deleting temporary directory '{0}'", outputDir)); Utils.DeleteDirectory(outputDir); @@ -468,7 +468,7 @@ internal void PushResource(string Repository, string modulePrefix, bool SkipDepe } else { - if(_isNupkgPathSpecified) + if (_isNupkgPathSpecified) { outputNupkgDir = pathToNupkgToPublish; } @@ -740,7 +740,8 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o error = new ErrorRecord(new ArgumentException($"Could not publish to repository '{repoName}'. The Credential provided was incorrect. Exception: '{e.Message}'"), "401Error", ErrorCategory.PermissionDenied, - this); ; + this); + ; } } else if (e.Message.Contains("403")) @@ -1126,7 +1127,7 @@ private string CreateNuspec( { XmlElement element = doc.CreateElement("dependency", nameSpaceUri); element.SetAttribute("id", dependencyName); - + string dependencyVersion = requiredModules[dependencyName].ToString(); if (!string.IsNullOrEmpty(dependencyVersion)) { @@ -1201,13 +1202,13 @@ private Hashtable ParseRequiredModules(Hashtable parsedMetadataHash) { string moduleName = moduleHash["ModuleName"] as string; var versionInfo = new Hashtable(); - + // RequiredVersion cannot be used with ModuleVersion or MaximumVersion if (moduleHash.ContainsKey("RequiredVersion")) { versionInfo["RequiredVersion"] = moduleHash["RequiredVersion"].ToString(); } - else + else { // ModuleVersion and MaximumVersion can be used together if (moduleHash.ContainsKey("ModuleVersion")) @@ -1418,11 +1419,11 @@ internal Hashtable GetMetadataFromNupkg(string copiedNupkgPath, string packageNa if (!Utils.TryReadManifestFile(psd1FilePath, out pkgMetadata, out Exception readManifestError)) { errRecord = new ErrorRecord( - readManifestError, - "GetMetadataFromNupkgFailure", - ErrorCategory.ParserError, + readManifestError, + "GetMetadataFromNupkgFailure", + ErrorCategory.ParserError, this); - + return pkgMetadata; } } @@ -1432,9 +1433,9 @@ internal Hashtable GetMetadataFromNupkg(string copiedNupkgPath, string packageNa if (!PSScriptFileInfo.TryTestPSScriptFileInfo(ps1FilePath, out PSScriptFileInfo parsedScript, out ErrorRecord[] errors, out string[] verboseMsgs)) { errRecord = new ErrorRecord( - new InvalidDataException($"PSScriptFile could not be read properly"), - "GetMetadataFromNupkgFailure", - ErrorCategory.ParserError, + new InvalidDataException($"PSScriptFile could not be read properly"), + "GetMetadataFromNupkgFailure", + ErrorCategory.ParserError, this); return pkgMetadata; @@ -1455,20 +1456,20 @@ internal Hashtable GetMetadataFromNupkg(string copiedNupkgPath, string packageNa { errRecord = new ErrorRecord( new InvalidDataException($".nupkg package must contain either .psd1, .ps1, or .nuspec file and none were found"), - "GetMetadataFromNupkgFailure", - ErrorCategory.InvalidData, + "GetMetadataFromNupkgFailure", + ErrorCategory.InvalidData, this); - + return pkgMetadata; } } catch (Exception e) { - errRecord = new ErrorRecord( - new InvalidOperationException($"Temporary folder for installation could not be created or set due to: {e.Message}"), - "GetMetadataFromNupkgFailure", - ErrorCategory.InvalidOperation, - this); + errRecord = new ErrorRecord( + new InvalidOperationException($"Temporary folder for installation could not be created or set due to: {e.Message}"), + "GetMetadataFromNupkgFailure", + ErrorCategory.InvalidOperation, + this); } finally { diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 524e86ae1..8aaa68052 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -44,7 +44,7 @@ public sealed class PublishPSResource : PSCmdlet, IDynamicParameters /// Specifies the path to the resource that you want to publish. This parameter accepts the path to the folder that contains the resource. /// Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). /// - [Parameter (Mandatory = true, Position = 0, ParameterSetName = PathParameterSet, HelpMessage = "Path to the resource to be published.")] + [Parameter(Mandatory = true, Position = 0, ParameterSetName = PathParameterSet, HelpMessage = "Path to the resource to be published.")] [ValidateNotNullOrEmpty] public string Path { get; set; } @@ -80,7 +80,8 @@ public sealed class PublishPSResource : PSCmdlet, IDynamicParameters /// [Parameter] [ValidateNotNullOrEmpty] - public Uri Proxy { + public Uri Proxy + { set { if (value != null) @@ -99,7 +100,8 @@ public Uri Proxy { /// [Parameter] [ValidateNotNullOrEmpty] - public PSCredential ProxyCredential { + public PSCredential ProxyCredential + { set { if (value != null) diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 97e18bdc9..4ff733a85 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -65,7 +65,7 @@ class RegisterPSResourceRepository : PSCmdlet /// [Parameter(Mandatory = true, ParameterSetName = RepositoriesParameterSet, HelpMessage = "Hashtable including information on single or multiple repositories to be registered.")] [ValidateNotNullOrEmpty] - public Hashtable[] Repository {get; set;} + public Hashtable[] Repository { get; set; } /// /// Specifies whether the repository should be trusted. @@ -328,7 +328,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) PSCredentialInfo repoCredentialInfo = null; if (repo.ContainsKey("CredentialInfo") && - !Utils.TryCreateValidPSCredentialInfo(credentialInfoCandidate: (PSObject) repo["CredentialInfo"], + !Utils.TryCreateValidPSCredentialInfo(credentialInfoCandidate: (PSObject)repo["CredentialInfo"], cmdletPassedIn: this, repoCredentialInfo: out repoCredentialInfo, errorRecord: out ErrorRecord errorRecord1)) @@ -359,7 +359,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : DefaultTrusted, - apiVersion: repo.ContainsKey("Trusted") ? (PSRepositoryInfo.APIVersion?) repo["ApiVersion"] : null, + apiVersion: repo.ContainsKey("Trusted") ? (PSRepositoryInfo.APIVersion?)repo["ApiVersion"] : null, repoCredentialInfo, Force, this, diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index e9f2693e2..714b95afb 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -303,7 +303,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, apiVersion, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsg); + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, apiVersion, 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. @@ -365,14 +365,14 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio { if (urlAttributeExists) { - if(!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl)) + if (!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl)) { throw new PSInvalidOperationException(String.Format("The 'Url' for repository {0} is invalid and the repository cannot be used. Please update the Url field or remove the repository entry.", repoName)); } } else { - if(!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl)) + if (!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl)) { throw new PSInvalidOperationException(String.Format("The 'Url' for repository {0} is invalid and the repository cannot be used. Please update the Url field or remove the repository entry.", repoName)); } @@ -447,7 +447,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; - RepositoryProviderType repositoryProvider= GetRepositoryProviderType(thisUrl); + RepositoryProviderType repositoryProvider = GetRepositoryProviderType(thisUrl); updatedRepo = new PSRepositoryInfo(repoName, thisUrl, Int32.Parse(node.Attribute("Priority").Value), @@ -537,7 +537,7 @@ public static List Remove(string[] repoNames, out string[] err bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true; - RepositoryProviderType repositoryProvider= GetRepositoryProviderType(repoUri); + RepositoryProviderType repositoryProvider = GetRepositoryProviderType(repoUri); removedRepos.Add( new PSRepositoryInfo(repo, new Uri(node.Attribute(attributeUrlUriName).Value), @@ -669,7 +669,7 @@ public static List Read(string[] repoNames, out string[] error continue; } - RepositoryProviderType repositoryProvider= GetRepositoryProviderType(thisUrl); + RepositoryProviderType repositoryProvider = GetRepositoryProviderType(thisUrl); bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; @@ -777,7 +777,7 @@ public static List Read(string[] repoNames, out string[] error continue; } - RepositoryProviderType repositoryProvider= GetRepositoryProviderType(thisUrl); + RepositoryProviderType repositoryProvider = GetRepositoryProviderType(thisUrl); bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; @@ -876,15 +876,18 @@ private static RepositoryProviderType GetRepositoryProviderType(Uri repoUri) { string absoluteUri = repoUri.AbsoluteUri; // We want to use contains instead of EndsWith to accomodate for trailing '/' - if (absoluteUri.Contains("azurecr.io") || absoluteUri.Contains("mcr.microsoft.com")){ + if (absoluteUri.Contains("azurecr.io") || absoluteUri.Contains("mcr.microsoft.com")) + { return RepositoryProviderType.ACR; } // TODO: add a regex for this match // eg: *pkgs.*/_packaging/* - else if (absoluteUri.Contains("pkgs.")){ + else if (absoluteUri.Contains("pkgs.")) + { return RepositoryProviderType.AzureDevOps; } - else { + else + { return RepositoryProviderType.None; } } diff --git a/src/code/ResponseUtil.cs b/src/code/ResponseUtil.cs index 40d6f9fc0..226c6bb44 100644 --- a/src/code/ResponseUtil.cs +++ b/src/code/ResponseUtil.cs @@ -28,6 +28,6 @@ public ResponseUtil(PSRepositoryInfo repository) public abstract IEnumerable ConvertToPSResourceResult(FindResults responseResults); #endregion - + } } diff --git a/src/code/SavePSResource.cs b/src/code/SavePSResource.cs index 26d481fce..4276ea9fb 100644 --- a/src/code/SavePSResource.cs +++ b/src/code/SavePSResource.cs @@ -168,7 +168,7 @@ public string TemporaryPath /// /// Suppresses progress information. /// - [Parameter] + [Parameter] public SwitchParameter Quiet { get; set; } /// diff --git a/src/code/ServerApiCall.cs b/src/code/ServerApiCall.cs index 4580e362e..6f363f478 100644 --- a/src/code/ServerApiCall.cs +++ b/src/code/ServerApiCall.cs @@ -31,10 +31,11 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if (networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; - }; + } + ; if (token) { @@ -43,12 +44,15 @@ public ServerApiCall(PSRepositoryInfo repository, NetworkCredential networkCrede _sessionClient = new HttpClient(handler); _sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - } else { + } + else + { handler.Credentials = networkCredential; _sessionClient = new HttpClient(handler); - }; + } + ; _sessionClient.Timeout = TimeSpan.FromMinutes(10); } diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index f90646fa2..325e02eba 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -143,15 +143,15 @@ protected override void ProcessRecord() List items = new List(); - switch(ParameterSetName) + switch (ParameterSetName) { case NameParameterSet: try { - items.Add(RepositorySettings.UpdateRepositoryStore(Name, - _uri, + items.Add(RepositorySettings.UpdateRepositoryStore(Name, + _uri, Priority, - Trusted, + Trusted, isSet, DefaultPriority, repoApiVersion, @@ -159,7 +159,7 @@ protected override void ProcessRecord() this, out string errorMsg)); - if (!string.IsNullOrEmpty(errorMsg)) + if (!string.IsNullOrEmpty(errorMsg)) { ThrowTerminatingError(new ErrorRecord( new PSInvalidOperationException(errorMsg), @@ -200,7 +200,7 @@ protected override void ProcessRecord() if (PassThru) { - foreach(PSRepositoryInfo item in items) + foreach (PSRepositoryInfo item in items) { WriteObject(item); } @@ -267,19 +267,19 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) isSet = false; if (repo.ContainsKey("Trusted")) { - repoTrusted = (bool) repo["Trusted"]; + repoTrusted = (bool)repo["Trusted"]; isSet = true; } PSCredentialInfo repoCredentialInfo = null; if (repo.ContainsKey("CredentialInfo") && - !Utils.TryCreateValidPSCredentialInfo(credentialInfoCandidate: (PSObject) repo["CredentialInfo"], + !Utils.TryCreateValidPSCredentialInfo(credentialInfoCandidate: (PSObject)repo["CredentialInfo"], cmdletPassedIn: this, repoCredentialInfo: out repoCredentialInfo, errorRecord: out ErrorRecord errorRecord1)) { WriteError(errorRecord1); - + return null; } diff --git a/src/code/UninstallPSResource.cs b/src/code/UninstallPSResource.cs index 4d7862fbb..0b79b3a83 100644 --- a/src/code/UninstallPSResource.cs +++ b/src/code/UninstallPSResource.cs @@ -102,13 +102,13 @@ protected override void ProcessRecord() else if (!Utils.TryParseVersionOrVersionRange(Version, out _versionRange)) { ThrowTerminatingError(new ErrorRecord( - new ArgumentException("Argument for -Version parameter is not in the proper format."), - "IncorrectVersionFormat", - ErrorCategory.InvalidArgument, + new ArgumentException("Argument for -Version parameter is not in the proper format."), + "IncorrectVersionFormat", + ErrorCategory.InvalidArgument, this)); } - Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool _); + Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] errorMsgs, out bool _); foreach (string error in errorMsgs) { @@ -136,7 +136,8 @@ protected override void ProcessRecord() break; case InputObjectParameterSet: - foreach (var inputObj in InputObject) { + foreach (var inputObj in InputObject) + { string inputObjectPrerelease = inputObj.Prerelease; string inputObjectVersion = String.IsNullOrEmpty(inputObjectPrerelease) ? inputObj.Version.ToString() : Utils.GetNormalizedVersionString(versionString: inputObj.Version.ToString(), prerelease: inputObjectPrerelease); if (!Utils.TryParseVersionOrVersionRange( @@ -144,9 +145,9 @@ protected override void ProcessRecord() versionRange: out _versionRange)) { WriteError(new ErrorRecord( - new ArgumentException($"Error parsing version '{inputObj.Version}' for resource '{inputObj.Name}'."), - "ErrorParsingVersion", - ErrorCategory.ParserError, + new ArgumentException($"Error parsing version '{inputObj.Version}' for resource '{inputObj.Name}'."), + "ErrorParsingVersion", + ErrorCategory.ParserError, this)); } @@ -154,8 +155,8 @@ protected override void ProcessRecord() if (!String.IsNullOrWhiteSpace(inputObj.Name) && !UninstallPkgHelper(out List InputObjErrRecords)) { foreach (var err in InputObjErrRecords) - { - WriteError(err); + { + WriteError(err); } } } @@ -185,7 +186,8 @@ private bool UninstallPkgHelper(out List errRecords) int totalDirs = dirsToDelete.Count; errRecords = new List(); - if (totalDirs == 0) { + if (totalDirs == 0) + { string message = Version == null || Version.Trim().Equals("*") ? $"Cannot uninstall resource '{String.Join(", ", Name)}' because it does not exist" : $"Cannot uninstall verison '{Version}' of resource '{String.Join(", ", Name)}' because it does not exist"; @@ -304,18 +306,18 @@ private bool UninstallModuleHelper(string pkgPath, string pkgName, out ErrorReco catch (Exception e) { errRecord = new ErrorRecord( - new ArgumentException($"Parent directory '{dir.Parent.FullName}' could not be deleted: {e.Message}"), - "ErrorDeletingParentDirectory", - ErrorCategory.InvalidArgument, + new ArgumentException($"Parent directory '{dir.Parent.FullName}' could not be deleted: {e.Message}"), + "ErrorDeletingParentDirectory", + ErrorCategory.InvalidArgument, this); } } catch (Exception err) { errRecord = new ErrorRecord( - new ArgumentException($"Parent directory '{dir.FullName}' could not be deleted: {err.Message}"), - "ErrorDeletingDirectory", - ErrorCategory.PermissionDenied, + new ArgumentException($"Parent directory '{dir.FullName}' could not be deleted: {err.Message}"), + "ErrorDeletingDirectory", + ErrorCategory.PermissionDenied, this); } @@ -356,17 +358,17 @@ private bool UninstallScriptHelper(string pkgPath, string pkgName, out ErrorReco catch (Exception e) { errRecord = new ErrorRecord( - new ArgumentException($"Script metadata file '{scriptXML}' could not be deleted: {e.Message}"), - "ErrorDeletingScriptMetadataFile", - ErrorCategory.PermissionDenied, + new ArgumentException($"Script metadata file '{scriptXML}' could not be deleted: {e.Message}"), + "ErrorDeletingScriptMetadataFile", + ErrorCategory.PermissionDenied, this); } } catch (Exception err) { errRecord = new ErrorRecord( - new ArgumentException($"Script '{pkgPath}' could not be deleted: {err.Message}"), - "ErrorDeletingScript", + new ArgumentException($"Script '{pkgPath}' could not be deleted: {err.Message}"), + "ErrorDeletingScript", ErrorCategory.PermissionDenied, this); } @@ -429,9 +431,10 @@ private bool CheckIfDependency(string pkgName, string version, out ErrorRecord e var parentPkg = parentPackages[i] as PSModuleInfo; for (int j = 0; j < parentPkg.RequiredModules.Count; j++) - { + { var pkgToUninstall = parentPkg.RequiredModules[j] as PSModuleInfo; - if (string.Equals(pkgToUninstall.Name, pkgName, StringComparison.InvariantCultureIgnoreCase)) { + if (string.Equals(pkgToUninstall.Name, pkgName, StringComparison.InvariantCultureIgnoreCase)) + { // then check verison if (pkgToUninstall.Version == null) { @@ -452,7 +455,8 @@ private bool CheckIfDependency(string pkgName, string version, out ErrorRecord e dependencyExists = true; } } - else { + else + { if (System.Version.TryParse(version, out systemVersion) && pkgToUninstall.Version.CompareTo(systemVersion) == 0) { // The required version OR module version is the version we're attempting to uninstall. diff --git a/src/code/UnregisterPSResourceRepository.cs b/src/code/UnregisterPSResourceRepository.cs index 09867ea20..1263ba0f8 100644 --- a/src/code/UnregisterPSResourceRepository.cs +++ b/src/code/UnregisterPSResourceRepository.cs @@ -45,7 +45,7 @@ protected override void BeginProcessing() } protected override void ProcessRecord() { - Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] _, out bool nameContainsWildcard); + Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] _, out bool nameContainsWildcard); if (nameContainsWildcard) { WriteError(new ErrorRecord( diff --git a/src/code/UpdateModuleManifest.cs b/src/code/UpdateModuleManifest.cs index 8ba86d87a..a4d0c82bf 100644 --- a/src/code/UpdateModuleManifest.cs +++ b/src/code/UpdateModuleManifest.cs @@ -23,7 +23,7 @@ public sealed class UpdateModuleManifest : PSCmdlet /// /// Specifies the path and file name of the module manifest. /// - [Parameter (Position = 0, Mandatory = true, HelpMessage = "Path (including file name) to the module manifest (.psd1 file) to update.")] + [Parameter(Position = 0, Mandatory = true, HelpMessage = "Path (including file name) to the module manifest (.psd1 file) to update.")] [ValidateNotNullOrEmpty] public string Path { get; set; } @@ -296,7 +296,7 @@ protected override void EndProcessing() } // Parse the module manifest - if(!Utils.TryReadManifestFile( + if (!Utils.TryReadManifestFile( manifestFilePath: resolvedManifestPath, manifestInfo: out Hashtable parsedMetadata, error: out Exception manifestReadError)) @@ -676,7 +676,8 @@ private void CreateModuleManifestHelper(Hashtable parsedMetadata, string resolve ErrorCategory.InvalidOperation, this); } - finally { + finally + { // Clean up temp file if move fails if (File.Exists(tmpModuleManifestPath)) { @@ -1036,7 +1037,8 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string ErrorCategory.InvalidOperation, this); } - finally { + finally + { // Clean up temp file if move fails if (File.Exists(tmpModuleManifestPath)) { @@ -1092,16 +1094,16 @@ Example PrivateData */ string tagsString = string.Join(", ", tags.Select(item => "'" + item + "'")); - string tagLine = tags.Length != 0 ? $"Tags = @({tagsString})" : "# Tags = @()"; + string tagLine = tags.Length != 0 ? $"Tags = @({tagsString})" : "# Tags = @()"; string licenseUriLine = licenseUri == null ? "# LicenseUri = ''" : $"LicenseUri = '{licenseUri.ToString()}'"; string projectUriLine = projectUri == null ? "# ProjectUri = ''" : $"ProjectUri = '{projectUri.ToString()}'"; string iconUriLine = iconUri == null ? "# IconUri = ''" : $"IconUri = '{iconUri.ToString()}'"; - string releaseNotesLine = String.IsNullOrEmpty(releaseNotes) ? "# ReleaseNotes = ''": $"ReleaseNotes = '{releaseNotes}'"; + string releaseNotesLine = String.IsNullOrEmpty(releaseNotes) ? "# ReleaseNotes = ''" : $"ReleaseNotes = '{releaseNotes}'"; string prereleaseLine = String.IsNullOrEmpty(prerelease) ? "# Prerelease = ''" : $"Prerelease = '{prerelease}'"; - string requireLicenseAcceptanceLine = requireLicenseAcceptance == null? "# RequireLicenseAcceptance = $false" : (requireLicenseAcceptance == false ? "RequireLicenseAcceptance = $false": "RequireLicenseAcceptance = $true"); + string requireLicenseAcceptanceLine = requireLicenseAcceptance == null ? "# RequireLicenseAcceptance = $false" : (requireLicenseAcceptance == false ? "RequireLicenseAcceptance = $false" : "RequireLicenseAcceptance = $true"); string externalModuleDependenciesString = string.Join(", ", externalModuleDependencies.Select(item => "'" + item + "'")); string externalModuleDependenciesLine = externalModuleDependencies.Length == 0 ? "# ExternalModuleDependencies = @()" : $"ExternalModuleDependencies = @({externalModuleDependenciesString})"; @@ -1153,7 +1155,8 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st // find line that is start of PrivateData entry for (int i = 0; i < psd1FileLines.Length; i++) { - if (psd1FileLines[i].Trim().StartsWith("PrivateData =")){ + if (psd1FileLines[i].Trim().StartsWith("PrivateData =")) + { privateDataStartLine = i; break; } @@ -1167,7 +1170,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st { leftBracket++; } - else if(psd1FileLines[i].Contains("}")) + else if (psd1FileLines[i].Contains("}")) { if (leftBracket > 0) { @@ -1200,7 +1203,7 @@ private bool TryCreateNewPsd1WithUpdatedPrivateData(string privateDataString, st } newPsd1Lines.Add(privateDataString); - for (int i = privateDataEndLine+1; i < psd1FileLines.Length; i++) + for (int i = privateDataEndLine + 1; i < psd1FileLines.Length; i++) { newPsd1Lines.Add(psd1FileLines[i]); } diff --git a/src/code/UpdatePSResource.cs b/src/code/UpdatePSResource.cs index 86e2cf1ae..63c502997 100644 --- a/src/code/UpdatePSResource.cs +++ b/src/code/UpdatePSResource.cs @@ -40,7 +40,7 @@ public sealed class UpdatePSResource : PSCmdlet [SupportsWildcards] [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] - public string[] Name { get; set ; } = new string[] {"*"}; + public string[] Name { get; set; } = new string[] { "*" }; /// /// Specifies the version the resource is to be updated to. @@ -85,11 +85,11 @@ public string TemporaryPath set { - if (WildcardPattern.ContainsWildcardCharacters(value)) - { - throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); - } - + if (WildcardPattern.ContainsWildcardCharacters(value)) + { + throw new PSArgumentException("Wildcard characters are not allowed in the temporary path."); + } + // This will throw if path cannot be resolved _tmpPath = GetResolvedProviderPathFromPSPath(value, out ProviderInfo provider).First(); } @@ -161,11 +161,11 @@ protected override void BeginProcessing() var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; _findHelper = new FindHelper( - cancellationToken: _cancellationTokenSource.Token, + cancellationToken: _cancellationTokenSource.Token, cmdletPassedIn: this, networkCredential: networkCred); - _installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred); + _installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred); } protected override void ProcessRecord() @@ -183,7 +183,7 @@ protected override void ProcessRecord() "IncorrectVersionFormat", ErrorCategory.InvalidArgument, this)); - + return; } @@ -262,10 +262,10 @@ private string[] ProcessPackageNames( namesToProcess = Utils.ProcessNameWildcards( pkgNames: namesToProcess, - removeWildcardEntries:false, + removeWildcardEntries: false, errorMsgs: out string[] errorMsgs, isContainWildcard: out bool _); - + foreach (string error in errorMsgs) { WriteError(new ErrorRecord( @@ -274,12 +274,12 @@ private string[] ProcessPackageNames( ErrorCategory.InvalidArgument, this)); } - + // This catches the case where namesToProcess wasn't passed in as null or empty, // but after filtering out unsupported wildcard names there are no elements left in namesToProcess. if (namesToProcess.Length == 0) { - return Utils.EmptyStrArray; + return Utils.EmptyStrArray; } if (String.Equals(namesToProcess[0], "*", StringComparison.InvariantCultureIgnoreCase)) @@ -311,7 +311,7 @@ private string[] ProcessPackageNames( "NoInstalledPackagesFoundWithNameProvided", ErrorCategory.InvalidOperation, this)); - + return Utils.EmptyStrArray; } diff --git a/src/code/UpdatePSScriptFileInfo.cs b/src/code/UpdatePSScriptFileInfo.cs index f54842d47..7d6ac8f2f 100644 --- a/src/code/UpdatePSScriptFileInfo.cs +++ b/src/code/UpdatePSScriptFileInfo.cs @@ -207,7 +207,7 @@ protected override void EndProcessing() ErrorCategory.InvalidArgument, this)); } - + ModuleSpecification[] validatedRequiredModuleSpecifications = Array.Empty(); if (RequiredModules != null && RequiredModules.Length > 0) { @@ -241,7 +241,7 @@ protected override void EndProcessing() WriteError(error); } - return; + return; } bool signatureRemoved = false; @@ -256,7 +256,7 @@ protected override void EndProcessing() ErrorCategory.InvalidOperation, this)); } - + signatureRemoved = true; } @@ -290,16 +290,16 @@ protected override void EndProcessing() return; } - + string tempScriptPath = null; try { tempScriptPath = System.IO.Path.GetTempFileName(); - File.WriteAllLines(tempScriptPath, updatedPSScriptFileContents); - File.Copy(tempScriptPath, resolvedPath, overwrite: true); + File.WriteAllLines(tempScriptPath, updatedPSScriptFileContents); + File.Copy(tempScriptPath, resolvedPath, overwrite: true); } - catch(Exception e) + catch (Exception e) { WriteError(new ErrorRecord( new PSInvalidOperationException($"Could not update .ps1 file due to: {e.Message}"), diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 5ca14d0e2..5162b6dad 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -141,7 +141,8 @@ public static string[] GetStringArrayFromString(string[] delimeter, string strin /// public static string[] GetStringArray(ArrayList list) { - if (list == null) { return null; } + if (list == null) + { return null; } var strArray = new string[list.Count]; for (int i = 0; i < list.Count; i++) @@ -353,7 +354,8 @@ public static bool TryParseVersionOrVersionRange( out VersionRange versionRange) { versionRange = null; - if (version == null) { return false; } + if (version == null) + { return false; } if (version.Trim().Equals("*")) { @@ -1609,7 +1611,7 @@ public static void DeleteDirectory(string dirPath) } // Remove read only file attributes first - foreach (var dirFilePath in Directory.GetFiles(dirPath,"*",SearchOption.AllDirectories)) + foreach (var dirFilePath in Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)) { if (File.GetAttributes(dirFilePath).HasFlag(FileAttributes.ReadOnly)) { @@ -1623,7 +1625,7 @@ public static void DeleteDirectory(string dirPath) { try { - Directory.Delete(dirPath,true); + Directory.Delete(dirPath, true); return; } catch (Exception ex) @@ -1870,11 +1872,11 @@ public static Hashtable GetMetadataFromNuspec(string nuspecFilePath, PSCmdlet cm try { XmlNodeList elemList = nuspecXmlDocument.GetElementsByTagName("metadata"); - for(int i = 0; i < elemList.Count; i++) + for (int i = 0; i < elemList.Count; i++) { XmlNode metadataInnerXml = elemList[i]; - for(int j= 0; j InvokeScriptWithHost( // Extract expected output types from results pipeline. foreach (var psItem in results) { - if (psItem == null || psItem.BaseObject == null) { continue; } + if (psItem == null || psItem.BaseObject == null) + { continue; } switch (psItem.BaseObject) { diff --git a/src/code/V2QueryBuilder.cs b/src/code/V2QueryBuilder.cs index c4891d5dd..8ece82780 100644 --- a/src/code/V2QueryBuilder.cs +++ b/src/code/V2QueryBuilder.cs @@ -25,7 +25,7 @@ internal class NuGetV2QueryBuilder /// If no criteria are added with , the built query string will not contain a $filter parameter unless is true. /// internal NuGetV2FilterBuilder FilterBuilder { get; private set; } - + /// /// Indicates whether an empty $filter parameter should be emitted if contains no criteria. /// @@ -80,7 +80,8 @@ internal string BuildQueryString() QueryParameters["$filter"] = FilterBuilder.BuildFilterString(); } - if (SearchTerm != null) { + if (SearchTerm != null) + { QueryParameters["searchTerm"] = SearchTerm; } @@ -221,4 +222,4 @@ public bool AddCriterion(string criterion) public int CriteriaCount => FilterCriteria.Count; } -} \ No newline at end of file +} diff --git a/src/code/V2ResponseUtil.cs b/src/code/V2ResponseUtil.cs index 4025f0c83..36fcde543 100644 --- a/src/code/V2ResponseUtil.cs +++ b/src/code/V2ResponseUtil.cs @@ -71,7 +71,8 @@ public override IEnumerable ConvertToPSResourceResult(FindResu #region V2 Specific Methods - public XmlNode[] ConvertResponseToXML(string httpResponse) { + public XmlNode[] ConvertResponseToXML(string httpResponse) + { NuGetVersion emptyVersion = new NuGetVersion("0.0.0.0"); NuGetVersion firstVersion = emptyVersion; NuGetVersion lastVersion = emptyVersion; @@ -84,7 +85,7 @@ public XmlNode[] ConvertResponseToXML(string httpResponse) { XmlNodeList entryNode = doc.GetElementsByTagName("entry"); XmlNode[] nodes = new XmlNode[entryNode.Count]; - for (int i = 0; i < entryNode.Count; i++) + for (int i = 0; i < entryNode.Count; i++) { XmlNode node = entryNode[i]; nodes[i] = node; diff --git a/src/code/V2ServerAPICalls.cs b/src/code/V2ServerAPICalls.cs index 38b5640de..5b3032499 100644 --- a/src/code/V2ServerAPICalls.cs +++ b/src/code/V2ServerAPICalls.cs @@ -39,7 +39,7 @@ internal class V2ServerAPICalls : ServerApiCall public override PSRepositoryInfo Repository { get; set; } private readonly PSCmdlet _cmdletPassedIn; private HttpClient _sessionClient { get; set; } - private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{}; + private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { }; public FindResponseType v2FindResponseType = FindResponseType.ResponseString; private bool _isADORepo; private bool _isJFrogRepo; @@ -49,17 +49,18 @@ internal class V2ServerAPICalls : ServerApiCall #region Constructor - public V2ServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base (repository, networkCredential) + public V2ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base(repository, networkCredential) { this.Repository = repository; _cmdletPassedIn = cmdletPassedIn; HttpClientHandler handler = new HttpClientHandler(); bool token = false; - if(networkCredential != null) + if (networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; - }; + } + ; if (token) { @@ -69,12 +70,15 @@ public V2ServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, N _sessionClient = new HttpClient(handler); _sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - } else { + } + else + { handler.Credentials = networkCredential; _sessionClient = new HttpClient(handler); - }; + } + ; _sessionClient.Timeout = TimeSpan.FromMinutes(10); _sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString); @@ -212,7 +216,7 @@ public override FindResults FindTags(string[] tags, bool includePrerelease, Reso _cmdletPassedIn.WriteDebug($"Count is '{count}'"); // skip 100 scriptSkip += 100; - var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord); + var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord); if (errRecord != null) { return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); @@ -351,12 +355,14 @@ public override FindResults FindName(string packageName, bool includePrerelease, // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion eq true" : "IsLatestVersion eq true"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -394,7 +400,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, response = string.Empty; } - return new FindResults(stringResponse: new string[]{ response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); + return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType); } /// @@ -420,12 +426,14 @@ public override FindResults FindNameWithTag(string packageName, string[] tags, b // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion eq true" : "IsLatestVersion eq true"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -646,12 +654,14 @@ public override FindResults FindVersion(string packageName, string version, Reso // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -713,12 +723,14 @@ public override FindResults FindVersionWithTag(string packageName, string versio // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'"); - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } @@ -908,29 +920,38 @@ private string FindAllFromTypeEndPoint(bool includePrerelease, bool isSearchingM }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } // JFrog/Artifactory requires an empty search term to enumerate all packages in the feed - if (_isJFrogRepo) { + if (_isJFrogRepo) + { queryBuilder.SearchTerm = "''"; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true"); - } else { + } + else + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsLatestVersion correctly filterBuilder.AddCriterion("IsLatestVersion eq true"); } } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } } @@ -960,25 +981,33 @@ private string FindTagFromEndpoint(string[] tags, bool includePrerelease, bool i }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; - if (_isJFrogRepo) { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); } - } else { - if (_isJFrogRepo) { + } + else + { + if (_isJFrogRepo) + { filterBuilder.AddCriterion("IsLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsLatestVersion"); } @@ -1010,26 +1039,34 @@ private string FindCommandOrDscResource(string[] tags, bool includePrerelease, b }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; - if (_isJFrogRepo) { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); } - } else { - if (_isJFrogRepo) { + } + else + { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsLatestVersion correctly filterBuilder.AddCriterion("IsLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsLatestVersion"); } @@ -1065,32 +1102,40 @@ private string FindNameGlobbing(string packageName, ResourceType type, bool incl }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; - if (_isJFrogRepo) { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); } - } else { - if (_isJFrogRepo) { + } + else + { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsLatestVersion correctly filterBuilder.AddCriterion("IsLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsLatestVersion"); } } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (names.Length == 0) { @@ -1149,7 +1194,8 @@ private string FindNameGlobbing(string packageName, ResourceType type, bool incl return string.Empty; } - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } var requestUrlV2 = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}"; @@ -1173,33 +1219,41 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, Resour }); var filterBuilder = queryBuilder.FilterBuilder; - if (_isPSGalleryRepo) { + if (_isPSGalleryRepo) + { queryBuilder.AdditionalParameters["$orderby"] = "Id desc"; } // JFrog/Artifactory requires an empty search term to enumerate all packages in the feed - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; - if (_isJFrogRepo) { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); } - } else { - if (_isJFrogRepo) { + } + else + { + if (_isJFrogRepo) + { // note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsLatestVersion correctly filterBuilder.AddCriterion("IsLatestVersion eq true"); } - else { + else + { // For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only filterBuilder.AddCriterion("IsLatestVersion"); } } - var names = packageName.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries); + var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); if (!_isPSGalleryRepo) { @@ -1263,7 +1317,8 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, Resour filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true"); } - if (type != ResourceType.None) { + if (type != ResourceType.None) + { filterBuilder.AddCriterion(GetTypeFilterForRequest(type)); } var requestUrlV2 = $"{Repository.Uri}/Search()?{queryBuilder.BuildQueryString()}"; @@ -1336,7 +1391,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange { maxPart = String.Format(format, operation, $"'{maxVersion.ToNormalizedString()}'"); } - else { + else + { maxPart = String.Format(format, operation, $"'{versionRange.MaxVersion.ToNormalizedString()}'"); } } @@ -1350,7 +1406,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange { filterBuilder.AddCriterion(maxPart); } - if (!includePrerelease) { + if (!includePrerelease) + { filterBuilder.AddCriterion("IsPrerelease eq false"); } @@ -1358,11 +1415,13 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange // If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id', // however filtering on 'and Title eq '' returns "Response status code does not indicate success: 500". - if (!_isJFrogRepo) { + if (!_isJFrogRepo) + { filterBuilder.AddCriterion($"Id eq '{packageName}'"); } - if (type == ResourceType.Script) { + if (type == ResourceType.Script) + { filterBuilder.AddCriterion($"substringof('PS{type.ToString()}', Tags) eq true"); } @@ -1421,7 +1480,8 @@ private Stream InstallVersion(string packageName, string version, out ErrorRecor return response.ReadAsStreamAsync().Result; } - private string GetTypeFilterForRequest(ResourceType type) { + private string GetTypeFilterForRequest(ResourceType type) + { string typeFilterPart = string.Empty; if (type == ResourceType.Script) { @@ -1474,7 +1534,7 @@ public int GetCountFromResponse(string httpResponse, out ErrorRecord errRecord) if (!countSearchSucceeded) { - // Note: not all V2 servers may have the 'count' property implemented or valid (i.e CloudSmith server), in this case try to get 'd:Id' property. + // Note: not all V2 servers may have the 'count' property implemented or valid (i.e CloudSmith server), in this case try to get 'd:Id' property. elemList = doc.GetElementsByTagName("d:Id"); if (elemList.Count > 0) { diff --git a/src/code/V3ServerAPICalls.cs b/src/code/V3ServerAPICalls.cs index c184426a8..e201511e3 100644 --- a/src/code/V3ServerAPICalls.cs +++ b/src/code/V3ServerAPICalls.cs @@ -28,7 +28,7 @@ internal class V3ServerAPICalls : ServerApiCall private bool _isGHPkgsRepo { get; set; } private bool _isMyGetRepo { get; set; } public FindResponseType v3FindResponseType = FindResponseType.ResponseString; - private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{}; + private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { }; private static readonly string nugetRepoUri = "https://api.nuget.org/v3/index.json"; private static readonly string resourcesName = "resources"; private static readonly string itemsName = "items"; @@ -55,10 +55,11 @@ public V3ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, Ne handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; bool token = false; - if(networkCredential != null) + if (networkCredential != null) { token = String.Equals("token", networkCredential.UserName) ? true : false; - }; + } + ; if (token) { @@ -68,12 +69,15 @@ public V3ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, Ne _sessionClient = new HttpClient(handler); _sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); - } else { + } + else + { handler.Credentials = networkCredential; - + _sessionClient = new HttpClient(handler); - }; + } + ; _sessionClient.Timeout = TimeSpan.FromMinutes(10); _sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString); @@ -1029,14 +1033,15 @@ private JsonElement[] GetMetadataElementFromIdLinkElement(JsonElement idLinkElem { _cmdletPassedIn.WriteDebug("In V3ServerAPICalls::GetMetadataElementFromIdLinkElement()"); upperVersion = String.Empty; - JsonElement[] innerItems = new JsonElement[]{}; + JsonElement[] innerItems = new JsonElement[] { }; List innerItemsList = new List(); string metadataUri = idLinkElement.ToString(); string response = HttpRequestCall(metadataUri, out errRecord); if (errRecord != null) { - if (errRecord.Exception is ResourceNotFoundException) { + if (errRecord.Exception is ResourceNotFoundException) + { errRecord = new ErrorRecord( new ResourceNotFoundException($"Package with name '{packageName}' could not be found in repository '{Repository.Name}'.", errRecord.Exception), "PackageNotFound", @@ -1072,7 +1077,7 @@ private JsonElement[] GetMetadataElementFromIdLinkElement(JsonElement idLinkElem _cmdletPassedIn.WriteDebug($"Package with name '{packageName}' did not have 'upper' property so package versions may not be in descending order."); } - foreach(JsonElement entry in innerItemsElement.EnumerateArray()) + foreach (JsonElement entry in innerItemsElement.EnumerateArray()) { // add clone, otherwise this JsonElement will be out of scope to the caller once JsonDocument is disposed innerItemsList.Add(entry.Clone()); @@ -1215,7 +1220,7 @@ private string[] GetMetadataElementsFromResponse(string response, string propert // This is when property is "packageContent" versionedPkgResponses.Add(metadataElement.ToString()); } - else if(metadataElement.ValueKind == JsonValueKind.Object) + else if (metadataElement.ValueKind == JsonValueKind.Object) { // This is when property is "catalogEntry" // If metadata has a "listed" property, but it's set to false, skip this package version @@ -1503,7 +1508,7 @@ private JsonElement[] GetJsonElementArr(string request, string propertyName, out string response = HttpRequestCall(request, out errRecord); if (errRecord != null) { - return new JsonElement[]{}; + return new JsonElement[] { }; } using (JsonDocument pkgsDom = JsonDocument.Parse(response)) @@ -1652,7 +1657,8 @@ private static async Task SendV3RequestAsync(HttpRequestMessage message, } catch (HttpRequestException e) { - if (responseStatusCode.Equals(HttpStatusCode.NotFound)) { + if (responseStatusCode.Equals(HttpStatusCode.NotFound)) + { throw new ResourceNotFoundException(Utils.FormatRequestsExceptions(e, message)); } // ADO feed will return a 401 if a package does not exist on the feed, with the following message: diff --git a/test/FindPSResourceTests/FindPSResourceADOV2Server.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceADOV2Server.Tests.ps1 index 253dad68e..998b88b71 100644 --- a/test/FindPSResourceTests/FindPSResourceADOV2Server.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceADOV2Server.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose "Current module search paths: $psmodulePaths" Describe 'Test HTTP Find-PSResource for ADO V2 Server Protocol' -tags 'CI' { - BeforeAll{ + BeforeAll { $testModuleName = "test_local_mod" $ADOV2RepoName = "PSGetTestingPublicFeed" $ADOV2RepoUri = "https://pkgs.dev.azure.com/powershell/PowerShell/_packaging/psresourceget-public-test-ci/nuget/v2" @@ -42,18 +42,18 @@ Describe 'Test HTTP Find-PSResource for ADO V2 Server Protocol' -tags 'CI' { $res.Count | Should -BeGreaterThan 1 } - $testCases2 = @{Version="[5.0.0]"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0, 5.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0, 5.0.0)"; ExpectedVersions=@("3.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0,)"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0,)"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0)"; ExpectedVersions=@("1.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0, 5.0.0)"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0, 5.0.0]"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} - - It "Find resource when given Name to " -TestCases $testCases2{ + $testCases2 = @{Version = "[5.0.0]"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match" }, + @{Version = "5.0.0"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0, 5.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0, 5.0.0)"; ExpectedVersions = @("3.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0,)"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0,)"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0)"; ExpectedVersions = @("1.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0, 5.0.0)"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0, 5.0.0]"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } + + It "Find resource when given Name to " -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $ADOV2RepoName @@ -92,7 +92,7 @@ Describe 'Test HTTP Find-PSResource for ADO V2 Server Protocol' -tags 'CI' { $resWithPrerelease.Count | Should -BeGreaterOrEqual $resWithoutPrerelease.Count } -<# LATER + <# LATER It "Find resource and its dependency resources with IncludeDependencies parameter" { # FindName() with deps $resWithoutDependencies = Find-PSResource -Name "TestModuleWithDependencyE" -Repository $ADOV2RepoName diff --git a/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 index 5b2de751b..dbc6c8f8d 100644 --- a/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 @@ -6,7 +6,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { - BeforeAll{ + BeforeAll { $testModuleName = "test-module" $testModuleWith2DigitVersion = "test-2DigitPkg" $testModuleParentName = "test_parent_mod" @@ -18,13 +18,10 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { $usingAzAuth = $env:USINGAZAUTH -eq 'true' - if ($usingAzAuth) - { + if ($usingAzAuth) { Write-Verbose -Verbose "Using Az module for authentication" Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -Verbose - } - else - { + } else { $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose } @@ -50,18 +47,18 @@ Describe 'Test HTTP Find-PSResource for ACR Server Protocol' -tags 'CI' { $res | Should -BeNullOrEmpty } - $testCases2 = @{Version="[5.0.0.0]"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0.0"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("3.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersions=@("1.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} + $testCases2 = @{Version = "[5.0.0.0]"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match" }, + @{Version = "5.0.0.0"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("3.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0.0)"; ExpectedVersions = @("1.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } - It "Find resource when given Name to " -TestCases $testCases2{ + It "Find resource when given Name to " -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $ACRRepoName @@ -306,7 +303,7 @@ Describe 'Test Find-PSResource for MAR Repository' -tags 'CI' { # Skip this test fo Describe 'Test Find-PSResource for unauthenticated ACR repository' -tags 'CI' { BeforeAll { - $skipOnWinPS = $PSVersionTable.PSVersion.Major -eq 5 + $skipOnWinPS = $PSVersionTable.PSVersion.Major -eq 5 if (-not $skipOnWinPS) { Register-PSResourceRepository -Name "Unauthenticated" -Uri "https://psresourcegetnoauth.azurecr.io/" -ApiVersion "ContainerRegistry" diff --git a/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 index 0d1dc4557..94cc61467 100644 --- a/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 @@ -7,7 +7,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test HTTP Find-PSResource for Github Packages Server' -tags 'CI' { Get-ChildItem -Path env: | Out-String | Write-Verbose -Verbose - BeforeAll{ + BeforeAll { $testModuleName = "test_module" $testScriptName = "test_script" $GithubPackagesRepoName = "GithubPackagesRepo" @@ -44,24 +44,23 @@ Describe 'Test HTTP Find-PSResource for Github Packages Server' -tags 'CI' { $res = Find-PSResource -Name $wildcardName -Repository $GithubPackagesRepoName -Credential $credential $res | Should -Not -BeNullOrEmpty $res.Count | Should -BeGreaterThan 1 - foreach ($item in $res) - { + foreach ($item in $res) { $item.Name | Should -BeLike $wildcardName } } - $testCases2 = @{Version="[5.0.0.0]"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0.0"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("3.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersions=@("1.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} + $testCases2 = @{Version = "[5.0.0.0]"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match" }, + @{Version = "5.0.0.0"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("3.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0.0)"; ExpectedVersions = @("1.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } - It "find resource when given Name to " -TestCases $testCases2{ + It "find resource when given Name to " -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $GithubPackagesRepoName -Credential $credential @@ -142,8 +141,7 @@ Describe 'Test HTTP Find-PSResource for Github Packages Server' -tags 'CI' { $nameWithWildcard = "test_*" $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTag -Repository $GithubPackagesRepoName -Credential $credential $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTag } @@ -162,8 +160,7 @@ Describe 'Test HTTP Find-PSResource for Github Packages Server' -tags 'CI' { $nameWithWildcard = "test_module*" $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTags -Repository $GithubPackagesRepoName -Credential $credential $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTags[0] $pkg.Tags | Should -Contain $requiredTags[1] diff --git a/test/FindPSResourceTests/FindPSResourceLocal.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceLocal.Tests.ps1 index 5c784fca2..7e72af21c 100644 --- a/test/FindPSResourceTests/FindPSResourceLocal.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceLocal.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose "Current module search paths: $psmodulePaths" Describe 'Test Find-PSResource for local repositories' -tags 'CI' { - BeforeAll{ + BeforeAll { $localRepo = "psgettestlocal" $localUNCRepo = 'psgettestlocal3' $testModuleName = "test_local_mod" @@ -121,18 +121,18 @@ Describe 'Test Find-PSResource for local repositories' -tags 'CI' { $res.Count | Should -BeGreaterThan 1 } - $testCases2 = @{Version="[5.0.0.0]"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0.0"; ExpectedVersions=@("5.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("3.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersions=@("1.0.0", "3.0.0", "5.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersions=@("1.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("1.0.0", "3.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("3.0.0", "5.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} - - It "find resource when given Name to " -TestCases $testCases2{ + $testCases2 = @{Version = "[5.0.0.0]"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match" }, + @{Version = "5.0.0.0"; ExpectedVersions = @("5.0.0"); Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("3.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersions = @("1.0.0", "3.0.0", "5.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0.0)"; ExpectedVersions = @("1.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0.0]"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("1.0.0", "3.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("3.0.0", "5.0.0"); Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } + + It "find resource when given Name to " -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $localRepo @@ -220,8 +220,7 @@ Describe 'Test Find-PSResource for local repositories' -tags 'CI' { $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTag -Repository $localRepo $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain "$requiredTag" } @@ -241,8 +240,7 @@ Describe 'Test Find-PSResource for local repositories' -tags 'CI' { $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTags -Repository $localRepo $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTags[0] $pkg.Tags | Should -Contain $requiredTags[1] @@ -286,7 +284,7 @@ Describe 'Test Find-PSResource for local repositories' -tags 'CI' { $res.Count | Should -Be 2 $res.Type | Should -Be @("Script", "Script") } - + It "find modules given -Type parameter" { Get-ScriptResourcePublishedToLocalRepoTestDrive "testScriptName" $localRepo "1.0.0" @@ -311,7 +309,7 @@ Describe 'Test Find-PSResource for local repositories' -tags 'CI' { $res = Find-PSResource -DscResourceName $dscResourceName -Repository $localRepo $res | Should -Not -BeNullOrEmpty foreach ($item in $res) { - $item.Names | Should -Be $dscResourceName + $item.Names | Should -Be $dscResourceName $item.ParentResource.Includes.DscResource | Should -Contain $dscResourceName } } diff --git a/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 index c350d0051..4323302c4 100644 --- a/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose "Current module search paths: $psmodulePaths" Describe 'Test Find-PSResource for searching and looping through repositories' -tags 'CI' { - BeforeAll{ + BeforeAll { $testModuleName = "test_module" $testModuleName2 = "test_module2" $testCmdDSCParentPkg = "myCmdDSCModule" @@ -78,7 +78,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should find resources that exist and not find ones that do not exist while reporting error (without -Repository specified)" { - $res = Find-PSResource -Name $testScriptName,"NonExistantModule" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name $testScriptName, "NonExistantModule" -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $res | Should -HaveCount 2 $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -101,7 +101,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find multiple resources from all repositories where it exists (without -Repository specified)" { - $res = Find-PSResource -Name $testModuleName,$testModuleName2 -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name $testModuleName, $testModuleName2 -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 0 $res | Should -HaveCount 5 @@ -134,17 +134,12 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundinLocalRepo = $false $pkgFoundinPSGallery = $false $pkgFoundinNuGetGallery = $false - foreach ($pkg in $res) - { - if ($pkg.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.Repository -eq $localRepoName) { $pkgFoundinLocalRepo = $true - } - elseif ($pkg.Repository -eq $PSGalleryName) { + } elseif ($pkg.Repository -eq $PSGalleryName) { $pkgFoundinPSGallery = $true - } - elseif ($pkg.Repository -eq $NuGetGalleryName) - { + } elseif ($pkg.Repository -eq $NuGetGalleryName) { $pkgFoundinNuGetGallery = $true } } @@ -176,7 +171,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "find resources from pattern matching repositories where it exists and error report for specific repositories (-Repository with wildcard and specific repositories)" -Pending { # Package "test_script" exists in the following repositories: PSGallery, NuGetGallery - $res = Find-PSResource -Name $testScriptName -Repository "*Gallery",$localRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name $testScriptName -Repository "*Gallery", $localRepoName -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $res | Should -HaveCount 2 $pkg1 = $res[0] @@ -193,7 +188,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "not find resources from pattern matching repositories if it doesn't exist and only write for for specific repositories (-Repository with wildcard and specific repositories)" -Pending { # Package "nonExistantPkg" does not exist in any repo - $res = Find-PSResource -Name "nonExistantPkg" -Repository "*Gallery",$localRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name "nonExistantPkg" -Repository "*Gallery", $localRepoName -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $res | Should -HaveCount 2 $pkg1 = $res[0] @@ -208,7 +203,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should not allow for repository name with wildcard and non-wildcard name specified in same command run" { - {Find-PSResource -Name "test_module" -Repository "*Gallery",$localRepoName} | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + { Find-PSResource -Name "test_module" -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "not find resource and write error if resource does not exist in any pattern matching repositories (-Repository with wildcard)" { @@ -245,7 +240,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource from all repositories where it exists (-Repository with multiple non-wildcard values)" { - $res = Find-PSResource -Name $testModuleName -Repository $PSGalleryName,$NuGetGalleryName + $res = Find-PSResource -Name $testModuleName -Repository $PSGalleryName, $NuGetGalleryName $res | Should -HaveCount 2 $pkg1 = $res[0] @@ -260,7 +255,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "find resource from all repositories where it exists and write errors for those it does not exist from (-Repository with multiple non-wildcard values)" { # Package "test_module3" exists in the following repositories: NuGetGalleryName $pkgOnNuGetGallery = "test_module3" - $res = Find-PSResource -Name $pkgOnNuGetGallery -Repository $PSGalleryName,$NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name $pkgOnNuGetGallery -Repository $PSGalleryName, $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 1 $err | Should -HaveCount 1 @@ -272,7 +267,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should not find resource from repositories where it does not exist and not write error since package Name contains wilcard" -Pending { - $res = Find-PSResource -Name "NonExistantPkg*" -Repository $PSGalleryName,$NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Name "NonExistantPkg*" -Repository $PSGalleryName, $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 0 $err | Should -HaveCount 0 } @@ -334,7 +329,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource when it has one tag specified but not other and report error (without -Repository specified)" { - $res = Find-PSResource -Tag $tag2,"NonExistantTag" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Tag $tag2, "NonExistantTag" -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 0 $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageWithTagsNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -348,7 +343,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource and discard Tag entry containing wildcard, but search for other non-wildcard Tag entries (without -Repository specified)" { - $res = Find-PSResource -Tag $tag2,"myTag*" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Tag $tag2, "myTag*" -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "WildcardsUnsupportedForTag,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -392,7 +387,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should not allow for repository name with wildcard and non-wildcard name specified in same command run" { - {Find-PSResource -Tag $tag1 -Repository "*Gallery",$localRepoName} | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + { Find-PSResource -Tag $tag1 -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "not find resource and write error if tag does not exist for resources in any pattern matching repositories (-Repository with wildcard)" { @@ -422,7 +417,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource from all repositories where it exists (-Repository with multiple non-wildcard values)" { - $res = Find-PSResource -Tag $tag2 -Repository $PSGalleryName,$NuGetGalleryName + $res = Find-PSResource -Tag $tag2 -Repository $PSGalleryName, $NuGetGalleryName $res.Count | Should -BeGreaterOrEqual 3 $pkg1 = $res[0] @@ -441,7 +436,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "find resource from all repositories where it exists and write errors for those it does not exist from (-Repository with multiple non-wildcard values)" { # Package eith Tag "Tag-TestMyLocalScript-1.0.0.0" exists in the following repositories: PSGallery $tagForPkgOnPSGallery = "Tag-TestMyLocalScript-1.0.0.0" - $res = Find-PSResource -Tag $tagForPkgOnPSGallery -Repository $PSGalleryName,$NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -Tag $tagForPkgOnPSGallery -Repository $PSGalleryName, $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res.Count | Should -BeGreaterOrEqual 2 $err | Should -HaveCount 1 @@ -465,14 +460,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -491,7 +482,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource when it has one CommandName specified but not other and report error (without -Repository specified)" { - $res = Find-PSResource -CommandName $cmdName,"NonExistantCommandName" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -CommandName $cmdName, "NonExistantCommandName" -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 0 $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageWithCmdOrDscNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -505,7 +496,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource and discard CommandName entry containing wildcard, but search for other non-wildcard CommandName entries (without -Repository specified)" { - $res = Find-PSResource -CommandName $cmdName,"myCommandName*" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -CommandName $cmdName, "myCommandName*" -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "WildcardsUnsupportedForCommandNameorDSCResourceName,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -513,14 +504,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -540,14 +527,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -559,7 +542,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should not allow for repository name with wildcard and non-wildcard command name specified in same command run" { - {Find-PSResource -CommandName $cmdName -Repository "*Gallery",$localRepoName} | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + { Find-PSResource -CommandName $cmdName -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "not find resource and write error if tag does not exist for resources in any pattern matching repositories (-Repository with wildcard)" { @@ -591,20 +574,16 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource given CommandName from all repositories where it exists (-Repository with multiple non-wildcard values)" { - $res = Find-PSResource -CommandName $cmdName -Repository $PSGalleryName,$localRepoName + $res = Find-PSResource -CommandName $cmdName -Repository $PSGalleryName, $localRepoName $res.Count | Should -BeGreaterOrEqual 9 $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -617,21 +596,17 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "find resource given CommandName from all repositories where it exists and write errors for those it does not exist from (-Repository with multiple non-wildcard values)" { # Package with Command "Get-MyCommand" exists in the following repositories: localRepo - $res = Find-PSResource -CommandName $cmdName2 -Repository $PSGalleryName,$localRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -CommandName $cmdName2 -Repository $PSGalleryName, $localRepoName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 1 $err | Should -HaveCount 1 $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -645,7 +620,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource given CommandName from repository where it exists and not find and write error for unsupported single specific repository (-Repository with single non-wildcard value)" { - $res = Find-PSResource -CommandName $cmdName -Repository $localRepoName,$NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -CommandName $cmdName -Repository $localRepoName, $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 1 $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -654,18 +629,12 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromPSGallery = $false $pkgFoundFromNuGetGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true - } - elseif($pkg.ParentResource.Repository -eq $NuGetGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $NuGetGalleryName) { $pkgFoundFromNuGetGallery = $true } } @@ -685,14 +654,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -711,7 +676,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource when it has one DSCResourceName specified but not other and report error (without -Repository specified)" { - $res = Find-PSResource -DscResourceName $dscName,"NonExistantDSCResourceName" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -DscResourceName $dscName, "NonExistantDSCResourceName" -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 0 $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "PackageWithCmdOrDscNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -725,7 +690,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "not find resource and discard DSCREsource entry containing wildcard, but search for other non-wildcard DSCResourceName entries (without -Repository specified)" { - $res = Find-PSResource -DscResourceName $dscName,"myDSCResourceName*" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -DscResourceName $dscName, "myDSCResourceName*" -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "WildcardsUnsupportedForCommandNameorDSCResourceName,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -733,14 +698,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -760,14 +721,10 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -779,7 +736,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "should not allow for repository name with wildcard and non-wildcard command name specified in same command run" { - {Find-PSResource -DscResourceName $dscName -Repository "*Gallery",$localRepoName} | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" + { Find-PSResource -DscResourceName $dscName -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" } It "not find resource and write error if tag does not exist for resources in any pattern matching repositories (-Repository with wildcard)" { @@ -812,20 +769,16 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource given DSCResourceName from all repositories where it exists (-Repository with multiple non-wildcard values)" { - $res = Find-PSResource -DscResourceName $dscName -Repository $PSGalleryName,$localRepoName + $res = Find-PSResource -DscResourceName $dscName -Repository $PSGalleryName, $localRepoName $res.Count | Should -BeGreaterOrEqual 3 $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -838,21 +791,17 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - It "find resource given DSCResourceName from all repositories where it exists and write errors for those it does not exist from (-Repository with multiple non-wildcard values)" { # Package with DSCResourceName "MyDSCResource" exists in the following repositories: localRepo - $res = Find-PSResource -DscResourceName $dscName2 -Repository $PSGalleryName,$localRepoName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -DscResourceName $dscName2 -Repository $PSGalleryName, $localRepoName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 1 $err | Should -HaveCount 1 $pkgFoundFromLocalRepo = $false $pkgFoundFromPSGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true } } @@ -866,7 +815,7 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - } It "find resource given DSCResourceName from repository where it exists and not find and write error for unsupported specific repository (-Repository with single non-wildcard value)" { - $res = Find-PSResource -DscResourceName $dscName -Repository $localRepoName,$NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue + $res = Find-PSResource -DscResourceName $dscName -Repository $localRepoName, $NuGetGalleryName -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -HaveCount 1 $err | Should -HaveCount 1 $err[0].FullyQualifiedErrorId | Should -BeExactly "FindCommandOrDscResourceFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.FindPSResource" @@ -875,18 +824,12 @@ Describe 'Test Find-PSResource for searching and looping through repositories' - $pkgFoundFromPSGallery = $false $pkgFoundFromNuGetGallery = $false - foreach ($pkg in $res) - { - if ($pkg.ParentResource.Repository -eq $localRepoName) - { + foreach ($pkg in $res) { + if ($pkg.ParentResource.Repository -eq $localRepoName) { $pkgFoundFromLocalRepo = $true - } - elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $PSGalleryName) { $pkgFoundFromPSGallery = $true - } - elseif($pkg.ParentResource.Repository -eq $NuGetGalleryName) - { + } elseif ($pkg.ParentResource.Repository -eq $NuGetGalleryName) { $pkgFoundFromNuGetGallery = $true } } diff --git a/test/FindPSResourceTests/FindPSResourceV2Server.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceV2Server.Tests.ps1 index 2a01c7677..a3e6d851b 100644 --- a/test/FindPSResourceTests/FindPSResourceV2Server.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceV2Server.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose -Message "Current module search paths: $psmodulePaths" Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { - BeforeAll{ + BeforeAll { $PSGalleryName = Get-PSGalleryName $testModuleName = "test_module" $testModuleNameWithUnlistedVersion = "test_module10" @@ -45,10 +45,8 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $res = Find-PSResource -Name "test_*" -Repository $PSGalleryName $res.Count | Should -BeGreaterThan 1 # should find Module and Script resources - foreach ($item in $res) - { - if ($item.Type -eq "Script") - { + foreach ($item in $res) { + if ($item.Type -eq "Script") { $foundScript = $true } } @@ -61,18 +59,18 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $res.Count | Should -BeGreaterThan 0 } - $testCases2 = @{Version="[5.0.0.0]"; ExpectedVersions=@("5.0.0.0"); Reason="validate version, exact match"}, - @{Version="5.0.0.0"; ExpectedVersions=@("5.0.0.0"); Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("1.0.0.0", "3.0.0.0", "5.0.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("3.0.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersions=@("3.0.0.0", "5.0.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersions=@("1.0.0.0", "3.0.0.0", "5.0.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersions=@("1.0.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersions=@("1.0.0.0", "3.0.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersions=@("1.0.0.0", "3.0.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 5.0.0.0]"; ExpectedVersions=@("3.0.0.0", "5.0.0.0"); Reason="validate version, mixed exclusive minimum and inclusive maximum version"} + $testCases2 = @{Version = "[5.0.0.0]"; ExpectedVersions = @("5.0.0.0"); Reason = "validate version, exact match" }, + @{Version = "5.0.0.0"; ExpectedVersions = @("5.0.0.0"); Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("1.0.0.0", "3.0.0.0", "5.0.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("3.0.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersions = @("3.0.0.0", "5.0.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersions = @("1.0.0.0", "3.0.0.0", "5.0.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0.0)"; ExpectedVersions = @("1.0.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0.0]"; ExpectedVersions = @("1.0.0.0", "3.0.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersions = @("1.0.0.0", "3.0.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 5.0.0.0]"; ExpectedVersions = @("3.0.0.0", "5.0.0.0"); Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } - It "find resource when given Name to " -TestCases $testCases2{ + It "find resource when given Name to " -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $PSGalleryName @@ -132,24 +130,16 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $foundDepCCorrectVersion = $false $foundDepD = $false $foundDepDCorrectVersion = $false - foreach ($pkg in $resWithDependencies) - { - if ($pkg.Name -eq "TestModuleWithDependencyE") - { + foreach ($pkg in $resWithDependencies) { + if ($pkg.Name -eq "TestModuleWithDependencyE") { $foundParentPkgE = $true - } - elseif ($pkg.Name -eq "TestModuleWithDependencyC") - { + } elseif ($pkg.Name -eq "TestModuleWithDependencyC") { $foundDepC = $true $foundDepCCorrectVersion = [System.Version]$pkg.Version -le [System.Version]"1.0" - } - elseif ($pkg.Name -eq "TestModuleWithDependencyB") - { + } elseif ($pkg.Name -eq "TestModuleWithDependencyB") { $foundDepB = $true $foundDepBCorrectVersion = [System.Version]$pkg.Version -ge [System.Version]"1.0" - } - elseif ($pkg.Name -eq "TestModuleWithDependencyD") - { + } elseif ($pkg.Name -eq "TestModuleWithDependencyD") { $foundDepD = $true $foundDepDCorrectVersion = [System.Version]$pkg.Version -le [System.Version]"1.0" } @@ -190,8 +180,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $res = Find-PSResource -Name "test*" -Type Module -Repository $PSGalleryName $res.Count | Should -BeGreaterThan 1 foreach ($item in $res) { - if ($item.Type -eq "Script") - { + if ($item.Type -eq "Script") { $foundScript = $True } } @@ -248,8 +237,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $nameWithWildcard = "test_module*" $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTag -Repository $PSGalleryName $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTag } @@ -268,8 +256,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $nameWithWildcard = "test_module*" $res = Find-PSResource -Name $nameWithWildcard -Tag $requiredTags -Repository $PSGalleryName $res.Count | Should -BeGreaterThan 1 - foreach ($pkg in $res) - { + foreach ($pkg in $res) { $pkg.Name | Should -BeLike $nameWithWildcard $pkg.Tags | Should -Contain $requiredTags[0] $pkg.Tags | Should -Contain $requiredTags[1] @@ -358,7 +345,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $res = Find-PSResource -CommandName $commandName -Repository $PSGalleryName $res | Should -Not -BeNullOrEmpty foreach ($item in $res) { - $item.Names | Should -Be $commandName + $item.Names | Should -Be $commandName $item.ParentResource.Includes.Command | Should -Contain $commandName } } @@ -367,11 +354,11 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { $res = Find-PSResource -DscResourceName $dscResourceName -Repository $PSGalleryName $res | Should -Not -BeNullOrEmpty foreach ($item in $res) { - $item.Names | Should -Be $dscResourceName + $item.Names | Should -Be $dscResourceName $item.ParentResource.Includes.DscResource | Should -Contain $dscResourceName } } - + It "find resource, but only show listed versions" { # testmodule99 version 1.0.0-beta1 is unlisted $res = Find-PSResource -Name "testmodule99" -Repository $PSGalleryName @@ -384,7 +371,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { It "find all resources within a version range, including prereleases" { $res = Find-PSResource -Name "PSReadLine" -Version "(2.0,2.1)" -Prerelease -Repository $PSGalleryName $res | Should -Not -BeNullOrEmpty - $res.Count | Should -BeGreaterOrEqual 7 + $res.Count | Should -BeGreaterOrEqual 7 } It "find a specific version using NuGet versioning bracket syntax" { @@ -423,7 +410,7 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'CI' { Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'ManualValidationOnly' { - BeforeAll{ + BeforeAll { $PSGalleryName = Get-PSGalleryName $testModuleName = "MicrosoftPowerBIMgmt" Get-NewPSResourceRepositoryFile @@ -444,10 +431,8 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'ManualValidat $foundPkgs = [System.Collections.Generic.HashSet[String]]::new() $duplicatePkgsFound = $false - foreach ($item in $res) - { - if ($foundPkgs.Contains($item.Name)) - { + foreach ($item in $res) { + if ($foundPkgs.Contains($item.Name)) { $duplicatePkgsFound = $true break } diff --git a/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 index 57064f3e8..98c7e6dda 100644 --- a/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose "Current module search paths: $psmodulePaths" Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { - BeforeAll{ + BeforeAll { $NuGetGalleryName = Get-NuGetGalleryName $testModuleName = 'test_module' Get-NewPSResourceRepositoryFile @@ -45,19 +45,19 @@ Describe 'Test HTTP Find-PSResource for V3 Server Protocol' -tags 'CI' { } $testCases2 = [hashtable[]]( - @{Version='[5.0.0.0]'; ExpectedVersions=@('5.0.0'); Reason='validate version, exact match'}, - @{Version='5.0.0.0'; ExpectedVersions=@('5.0.0'); Reason='validate version, exact match without bracket syntax'}, - @{Version='[1.0.0.0, 5.0.0.0]'; ExpectedVersions=@('1.0.0', '3.0.0', '5.0.0'); Reason='validate version, exact range inclusive'}, - @{Version='(1.0.0.0, 5.0.0.0)'; ExpectedVersions=@('3.0.0'); Reason='validate version, exact range exclusive'}, - @{Version='(1.0.0.0,)'; ExpectedVersions=@('3.0.0', '5.0.0'); Reason='validate version, minimum version exclusive'}, - @{Version='[1.0.0.0,)'; ExpectedVersions=@('1.0.0', '3.0.0', '5.0.0'); Reason='validate version, minimum version inclusive'}, - @{Version='(,3.0.0.0)'; ExpectedVersions=@('1.0.0'); Reason='validate version, maximum version exclusive'}, - @{Version='(,3.0.0.0]'; ExpectedVersions=@('1.0.0', '3.0.0'); Reason='validate version, maximum version inclusive'}, - @{Version='[1.0.0.0, 5.0.0.0)'; ExpectedVersions=@('1.0.0', '3.0.0'); Reason='validate version, mixed inclusive minimum and exclusive maximum version'}, - @{Version='(1.0.0.0, 5.0.0.0]'; ExpectedVersions=@('3.0.0', '5.0.0'); Reason='validate version, mixed exclusive minimum and inclusive maximum version'} + @{Version = '[5.0.0.0]'; ExpectedVersions = @('5.0.0'); Reason = 'validate version, exact match' }, + @{Version = '5.0.0.0'; ExpectedVersions = @('5.0.0'); Reason = 'validate version, exact match without bracket syntax' }, + @{Version = '[1.0.0.0, 5.0.0.0]'; ExpectedVersions = @('1.0.0', '3.0.0', '5.0.0'); Reason = 'validate version, exact range inclusive' }, + @{Version = '(1.0.0.0, 5.0.0.0)'; ExpectedVersions = @('3.0.0'); Reason = 'validate version, exact range exclusive' }, + @{Version = '(1.0.0.0,)'; ExpectedVersions = @('3.0.0', '5.0.0'); Reason = 'validate version, minimum version exclusive' }, + @{Version = '[1.0.0.0,)'; ExpectedVersions = @('1.0.0', '3.0.0', '5.0.0'); Reason = 'validate version, minimum version inclusive' }, + @{Version = '(,3.0.0.0)'; ExpectedVersions = @('1.0.0'); Reason = 'validate version, maximum version exclusive' }, + @{Version = '(,3.0.0.0]'; ExpectedVersions = @('1.0.0', '3.0.0'); Reason = 'validate version, maximum version inclusive' }, + @{Version = '[1.0.0.0, 5.0.0.0)'; ExpectedVersions = @('1.0.0', '3.0.0'); Reason = 'validate version, mixed inclusive minimum and exclusive maximum version' }, + @{Version = '(1.0.0.0, 5.0.0.0]'; ExpectedVersions = @('3.0.0', '5.0.0'); Reason = 'validate version, mixed exclusive minimum and inclusive maximum version' } ) - It 'find resource when given Name to ' -TestCases $testCases2{ + It 'find resource when given Name to ' -TestCases $testCases2 { # FindVersionGlobbing() param($Version, $ExpectedVersions) $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName diff --git a/test/GetInstalledPSResource/GetInstalledPSResource.Tests.ps1 b/test/GetInstalledPSResource/GetInstalledPSResource.Tests.ps1 index 1f6feab66..bdc837093 100644 --- a/test/GetInstalledPSResource/GetInstalledPSResource.Tests.ps1 +++ b/test/GetInstalledPSResource/GetInstalledPSResource.Tests.ps1 @@ -7,7 +7,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test Get-InstalledPSResource for Module' -tags 'CI' { - BeforeAll{ + BeforeAll { $PSGalleryName = Get-PSGalleryName $testModuleName = "test_module" $testScriptName = "test_script" @@ -44,26 +44,26 @@ Describe 'Test Get-InstalledPSResource for Module' -tags 'CI' { } It "Get resource when given Name to " -TestCases @( - @{Name="*est_modul*"; ExpectedName=$testModuleName; Reason="validate name, with wildcard at beginning and end of name: *est_modul*"}, - @{Name="test_mod*"; ExpectedName=$testModuleName; Reason="validate name, with wildcard at end of name: test_mod*"}, - @{Name="*est_module"; ExpectedName=$testModuleName; Reason="validate name, with wildcard at beginning of name: *est_module"}, - @{Name="tes*ule"; ExpectedName=$testModuleName; Reason="validate name, with wildcard in middle of name: tes*ule"} + @{Name = "*est_modul*"; ExpectedName = $testModuleName; Reason = "validate name, with wildcard at beginning and end of name: *est_modul*" }, + @{Name = "test_mod*"; ExpectedName = $testModuleName; Reason = "validate name, with wildcard at end of name: test_mod*" }, + @{Name = "*est_module"; ExpectedName = $testModuleName; Reason = "validate name, with wildcard at beginning of name: *est_module" }, + @{Name = "tes*ule"; ExpectedName = $testModuleName; Reason = "validate name, with wildcard in middle of name: tes*ule" } ) { param($Version, $ExpectedVersion) $pkgs = Get-InstalledPSResource -Name $Name $pkgs.Name | Should -Contain $testModuleName } -$testCases = - @{Version="[1.0.0.0]"; ExpectedVersion="1.0.0.0"; Reason="validate version, exact match"}, - @{Version="1.0.0.0"; ExpectedVersion="1.0.0.0"; Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersion=@("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersion=@("3.0.0.0"); Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersion=@("5.0.0.0", "3.0.0.0"); Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersion=@("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason="validate version, minimum version inclusive"}, - @{Version="(,5.0.0.0)"; ExpectedVersion=@("3.0.0.0", "1.0.0.0"); Reason="validate version, maximum version exclusive"}, - @{Version="(,5.0.0.0]"; ExpectedVersion=@("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersion=@("3.0.0.0", "1.0.0.0"); Reason="validate version, mixed inclusive minimum and exclusive maximum version"} + $testCases = + @{Version = "[1.0.0.0]"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, exact match" }, + @{Version = "1.0.0.0"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersion = @("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersion = @("3.0.0.0"); Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersion = @("5.0.0.0", "3.0.0.0"); Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersion = @("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason = "validate version, minimum version inclusive" }, + @{Version = "(,5.0.0.0)"; ExpectedVersion = @("3.0.0.0", "1.0.0.0"); Reason = "validate version, maximum version exclusive" }, + @{Version = "(,5.0.0.0]"; ExpectedVersion = @("5.0.0.0", "3.0.0.0", "1.0.0.0"); Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersion = @("3.0.0.0", "1.0.0.0"); Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } It "Get resource when given Name to " -TestCases $testCases { param($Version, $ExpectedVersion) @@ -73,30 +73,29 @@ $testCases = } It "Throw invalid version error when passing incorrectly formatted version such as " -TestCases @( - @{Version='[1.*.0]'; Description="version with wilcard in middle"}, - @{Version='[*.0.0.0]'; Description="version with wilcard at start"}, - @{Version='[1.*.0.0]'; Description="version with wildcard at second digit"}, - @{Version='[1.0.*.0]'; Description="version with wildcard at third digit"} - @{Version='[1.0.0.*'; Description="version with wildcard at end"}, - @{Version='[1..0.0]'; Description="version with missing digit in middle"}, - @{Version='[1.0.0.]'; Description="version with missing digit at end"}, - @{Version='[1.0.0.0.0]'; Description="version with more than 4 digits"} + @{Version = '[1.*.0]'; Description = "version with wilcard in middle" }, + @{Version = '[*.0.0.0]'; Description = "version with wilcard at start" }, + @{Version = '[1.*.0.0]'; Description = "version with wildcard at second digit" }, + @{Version = '[1.0.*.0]'; Description = "version with wildcard at third digit" } + @{Version = '[1.0.0.*'; Description = "version with wildcard at end" }, + @{Version = '[1..0.0]'; Description = "version with missing digit in middle" }, + @{Version = '[1.0.0.]'; Description = "version with missing digit at end" }, + @{Version = '[1.0.0.0.0]'; Description = "version with more than 4 digits" } ) { param($Version, $Description) $res = $null try { $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $PSGalleryName -ErrorAction Ignore - } - catch {} - + } catch {} + $res | Should -BeNullOrEmpty } # These versions technically parse into proper NuGet versions, but will not return the version expected It "Does not return resource when passing incorrectly formatted version such as , does not throw error" -TestCases @( - @{Version='(1.0.0.0)'; Description="exlcusive version (8.1.0.0)"}, - @{Version='[1-0-0-0]'; Description="version formatted with invalid delimiter"} + @{Version = '(1.0.0.0)'; Description = "exlcusive version (8.1.0.0)" }, + @{Version = '[1-0-0-0]'; Description = "version formatted with invalid delimiter" } ) { param($Version, $Description) @@ -104,9 +103,8 @@ $testCases = $res = $null try { $res = Find-PSResource -Name $testModuleName -Version $Version -Repository $PSGalleryName -ErrorAction Ignore - } - catch {} - + } catch {} + $res | Should -BeNullOrEmpty } @@ -144,8 +142,8 @@ $testCases = (Get-Alias Get-PSResource).Definition | Should -BeExactly 'Get-InstalledPSResource' } - # Windows only - It "Get resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { + # Windows only + It "Get resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { $pkg = Get-InstalledPSResource -Name $testModuleName -Scope CurrentUser $pkg[0].Name | Should -Be $testModuleName $pkg[0].InstalledLocation.ToString().Contains("Documents") | Should -Be $true @@ -181,4 +179,4 @@ $testCases = $pkg.Name | Should -contain "testmodule99" $pkg.InstalledLocation.ToString().Contains("/.local") | Should -Be $true } -} \ No newline at end of file +} diff --git a/test/GroupPolicyEnforcement.Tests.ps1 b/test/GroupPolicyEnforcement.Tests.ps1 index 2353056e2..c57707bdf 100644 --- a/test/GroupPolicyEnforcement.Tests.ps1 +++ b/test/GroupPolicyEnforcement.Tests.ps1 @@ -26,8 +26,7 @@ Describe 'GroupPolicyEnforcement API Tests' -Tags 'CI' { $allowedReps = [Microsoft.PowerShell.PSResourceGet.Cmdlets.GroupPolicyRepositoryEnforcement]::GetAllowedRepositoryURIs() $allowedReps.AbsoluteUri | Should -Be @("https://www.example.com/") - } - finally { + } finally { [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('EnableGPRegistryHook', $false) [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('GPEnabledStatus', $false) [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('AllowedUri', $null) @@ -54,8 +53,7 @@ Describe 'GroupPolicyEnforcement Cmdlet Tests' -Tags 'CI' { $psrep = Get-PSResourceRepository -Name 'Example' $psrep | Should -Not -BeNullOrEmpty $psrep.IsAllowedByPolicy | Should -BeTrue - } - finally { + } finally { Unregister-PSResourceRepository -Name 'Example' } } @@ -68,8 +66,7 @@ Describe 'GroupPolicyEnforcement Cmdlet Tests' -Tags 'CI' { # Allow PSGallery and it should not fail [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('AllowedUri', " https://www.powershellgallery.com/api/v2") { Find-PSResource -Repository PSGallery -Name 'Az.Accounts' -ErrorAction Stop } | Should -Not -Throw - } - finally { + } finally { Unregister-PSResourceRepository -Name 'Example' } } @@ -81,9 +78,8 @@ Describe 'GroupPolicyEnforcement Cmdlet Tests' -Tags 'CI' { # Allow PSGallery and it should not fail [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('AllowedUri', " https://www.powershellgallery.com/api/v2") - { Install-PSResource -Repository PSGallery -Name 'Az.Accounts' -ErrorAction Stop -TrustRepository} | Should -Not -Throw - } - finally { + { Install-PSResource -Repository PSGallery -Name 'Az.Accounts' -ErrorAction Stop -TrustRepository } | Should -Not -Throw + } finally { Unregister-PSResourceRepository -Name 'Example' } } @@ -95,9 +91,8 @@ Describe 'GroupPolicyEnforcement Cmdlet Tests' -Tags 'CI' { # Allow PSGallery and it should not fail [Microsoft.PowerShell.PSResourceGet.UtilClasses.InternalHooks]::SetTestHook('AllowedUri', " https://www.powershellgallery.com/api/v2") - { Save-PSResource -Repository PSGallery -Name 'Az.Accounts' -ErrorAction Stop -TrustRepository} | Should -Not -Throw - } - finally { + { Save-PSResource -Repository PSGallery -Name 'Az.Accounts' -ErrorAction Stop -TrustRepository } | Should -Not -Throw + } finally { Unregister-PSResourceRepository -Name 'Example' } } diff --git a/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 index fbf32c59e..f14d01575 100644 --- a/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 @@ -25,9 +25,9 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = @{Name = "*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test_local_m*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test?local", "Test[local"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } It "Should not install resource with wildcard in name" -TestCases $testCases { param($Name, $ErrorId) @@ -101,8 +101,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $Version = "(1.0.0.0)" try { Install-PSResource -Name $testModuleName -Version $Version -Repository $ADORepoName -TrustRepository -ErrorAction SilentlyContinue - } - catch + } catch {} $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" diff --git a/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 index 589bff92b..25e300a73 100644 --- a/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 @@ -25,9 +25,9 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_local_m*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?local","Test[local"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = @{Name = "*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test_local_m*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test?local", "Test[local"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } It "Should not install resource with wildcard in name" -TestCases $testCases { param($Name, $ErrorId) @@ -101,8 +101,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $Version = "(1.0.0.0)" try { Install-PSResource -Name $testModuleName -Version $Version -Repository $ADORepoName -TrustRepository -ErrorAction SilentlyContinue - } - catch + } catch {} $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" diff --git a/test/InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1 index 5f80ace08..9df2dad64 100644 --- a/test/InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1 @@ -22,12 +22,9 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { $usingAzAuth = $env:USINGAZAUTH -eq 'true' - if ($usingAzAuth) - { + if ($usingAzAuth) { Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -Verbose - } - else - { + } else { $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose } @@ -41,9 +38,9 @@ Describe 'Test Install-PSResource for ACR scenarios' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test-mod*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?modu","Test[module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = @{Name = "*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test-mod*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test?modu", "Test[module"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } It "Should not install resource with wildcard in name" -TestCases $testCases { param($Name, $ErrorId) @@ -366,8 +363,7 @@ Describe 'Test Install-PSResource for MAR Repository' -tags 'CI' { $pkg = Install-PSResource -Name "Az.Accounts" -Repository "MAR" -PassThru -TrustRepository -Reinstall $pkg.Name | Should -Be "Az.Accounts" $pkg.Version | Should -Be "3.0.4" - } - finally { + } finally { if ($pkg) { Uninstall-PSResource -Name "Az.Accounts" -Version "3.0.4" } diff --git a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 index 0dafca8dc..60c7c3ac4 100644 --- a/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceGithubPackages.Tests.ps1 @@ -30,9 +30,9 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { Get-RevertPSResourceRepositoryFile } - $testCases = @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_m*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?module","Test[module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = @{Name = "*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test_m*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test?module", "Test[module"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } It "Should not install resource with wildcard in name" -TestCases $testCases { param($Name, $ErrorId) @@ -59,7 +59,7 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { It "Install multiple resources by name" { $pkgNames = @($testModuleName, $testModuleName2) - Install-PSResource -Name $pkgNames -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository + Install-PSResource -Name $pkgNames -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $pkgNames $pkg.Name | Should -Be $pkgNames } @@ -69,7 +69,7 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { $pkg = Get-InstalledPSResource "NonExistantModule" -ErrorAction SilentlyContinue $pkg | Should -BeNullOrEmpty $err.Count | Should -BeGreaterThan 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" } # Do some version testing, but Find-PSResource should be doing thorough testing @@ -81,21 +81,21 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { } It "Should install resource given name and exact version with bracket syntax" { - Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository + Install-PSResource -Name $testModuleName -Version "[1.0.0]" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "1.0.0" } It "Should install resource given name and exact range inclusive [1.0.0, 5.0.0]" { - Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository + Install-PSResource -Name $testModuleName -Version "[1.0.0, 5.0.0]" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.0.0" } It "Should install resource given name and exact range exclusive (1.0.0, 5.0.0)" { - Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository + Install-PSResource -Name $testModuleName -Version "(1.0.0, 5.0.0)" -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "3.0.0" @@ -106,8 +106,7 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { $Version = "(1.0.0.0)" try { Install-PSResource -Name $testModuleName -Version $Version -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository -ErrorAction SilentlyContinue - } - catch + } catch {} $Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" @@ -123,7 +122,7 @@ Describe 'Test Install-PSResource for GitHub packages' -tags 'CI' { } It "Install resource with latest (including prerelease) version given Prerelease parameter" { - Install-PSResource -Name $testModuleName -Prerelease -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository + Install-PSResource -Name $testModuleName -Prerelease -Repository $GithubPackagesRepoName -Credential $credential -TrustRepository $pkg = Get-InstalledPSResource $testModuleName $pkg.Name | Should -Be $testModuleName $pkg.Version | Should -Be "5.2.5" @@ -244,15 +243,15 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidatio It "Install resource under AllUsers scope - Unix only" -Skip:(Get-IsWindows) { Install-PSResource -Name $testModuleName -Repository $TestGalleryName -Scope AllUsers $pkg = Get-Module $testModuleName -ListAvailable - $pkg.Name | Should -Be $testModuleName + $pkg.Name | Should -Be $testModuleName $pkg.Path.Contains("/usr/") | Should -Be $true } # This needs to be manually tested due to prompt It "Install resource that requires accept license without -AcceptLicense flag" { Install-PSResource -Name $testModuleName2 -Repository $TestGalleryName - $pkg = Get-InstalledPSResource $testModuleName2 - $pkg.Name | Should -Be $testModuleName2 + $pkg = Get-InstalledPSResource $testModuleName2 + $pkg.Name | Should -Be $testModuleName2 $pkg.Version | Should -Be "0.0.1.0" } @@ -261,7 +260,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'ManualValidatio Set-PSResourceRepository PoshTestGallery -Trusted:$false Install-PSResource -Name $testModuleName -Repository $TestGalleryName -confirm:$false - + $pkg = Get-Module $testModuleName -ListAvailable $pkg.Name | Should -Be $testModuleName diff --git a/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 index f5ec1d02b..82188fc4b 100644 --- a/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 @@ -108,8 +108,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' { $Version = "(1.0.0.0)" try { Install-PSResource -Name $testModuleName -Version $Version -Repository $localRepo -TrustRepository -ErrorAction SilentlyContinue - } - catch + } catch {} $Error[0].FullyQualifiedErrorId | Should -Be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" diff --git a/test/InstallPSResourceTests/InstallPSResourceRepositorySearching.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceRepositorySearching.Tests.ps1 index 3ba5b97fa..67620026e 100644 --- a/test/InstallPSResourceTests/InstallPSResourceRepositorySearching.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceRepositorySearching.Tests.ps1 @@ -9,7 +9,7 @@ Write-Verbose -Verbose "Current module search paths: $psmodulePaths" Describe 'Test Install-PSResource for searching and looping through repositories' -tags 'CI' { - BeforeAll{ + BeforeAll { $testModuleName = "test_module" $testModule2Name = "test_module2" $testLocalModuleName = "test_local_mod" @@ -54,7 +54,7 @@ Describe 'Test Install-PSResource for searching and looping through repositories } It "should install resources that exist and not install ones that do not exist while reporting error (without -Repository specified)" { - Install-PSResource -Name $testScriptName,"NonExistantModule" -TrustRepository -SkipDependencyCheck -ErrorVariable err -ErrorAction SilentlyContinue + Install-PSResource -Name $testScriptName, "NonExistantModule" -TrustRepository -SkipDependencyCheck -ErrorVariable err -ErrorAction SilentlyContinue $err[0].FullyQualifiedErrorId | Should -BeExactly "InstallPackageFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" $res = Get-InstalledPSResource $testScriptName @@ -69,7 +69,7 @@ Describe 'Test Install-PSResource for searching and looping through repositories } It "install multiple resources from highest priority repository where it exists (without -Repository specified)" { - $res = Install-PSResource -Name "test_module","test_module2" -TrustRepository -SkipDependencyCheck -ErrorVariable err -ErrorAction SilentlyContinue -PassThru + $res = Install-PSResource -Name "test_module", "test_module2" -TrustRepository -SkipDependencyCheck -ErrorVariable err -ErrorAction SilentlyContinue -PassThru $err | Should -HaveCount 0 $res | Should -Not -BeNullOrEmpty @@ -93,9 +93,9 @@ Describe 'Test Install-PSResource for searching and looping through repositories } It "should not allow for repository name with wildcard and non-wildcard name specified in same command run" { - { Install-PSResource -Name $testModuleName -Repository "*Gallery",$localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + { Install-PSResource -Name $testModuleName -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" } - + It "not install resource and write error if resource does not exist in any pattern matching repositories (-Repository with wildcard)" { Install-PSResource -Name "nonExistantModule" -Repository "*Gallery" -TrustRepository -SkipDependencyCheck -ErrorVariable err -ErrorAction SilentlyContinue $err | Should -HaveCount 1 @@ -116,7 +116,7 @@ Describe 'Test Install-PSResource for searching and looping through repositories } It "install resource from highest priority repository where it exists (-Repository with multiple non-wildcard values)" { - $res = Install-PSResource -Name $testModuleName -Repository $PSGalleryName,$NuGetGalleryName -SkipDependencyCheck -TrustRepository -PassThru + $res = Install-PSResource -Name $testModuleName -Repository $PSGalleryName, $NuGetGalleryName -SkipDependencyCheck -TrustRepository -PassThru $res | Should -HaveCount 1 $res.Name | Should -Be $testModuleName @@ -124,7 +124,7 @@ Describe 'Test Install-PSResource for searching and looping through repositories } It "should not allow for repository name with wildcard and non-wildcard name specified in same command run" { - {Install-PSResource -Name $testModuleName -Repository "*Gallery",$localRepoName} | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" + { Install-PSResource -Name $testModuleName -Repository "*Gallery", $localRepoName } | Should -Throw -ErrorId "RepositoryNamesWithWildcardsAndNonWildcardUnsupported,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" } It "should not write error when package to install is already installed and -reinstall is not provided" { diff --git a/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 index 0b03a984b..e332a9107 100644 --- a/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 @@ -31,7 +31,7 @@ Describe 'Test Install-PSResource for V2 Server scenarios' -tags 'CI' { AfterEach { Uninstall-PSResource "test_module", "test_module2", "test_script", "TestModule99", "testModuleWithlicense", ` - "TestFindModule","ClobberTestModule1", "ClobberTestModule2", "PackageManagement", "TestTestScript", ` + "TestFindModule", "ClobberTestModule1", "ClobberTestModule2", "PackageManagement", "TestTestScript", ` "TestModuleWithDependency", "TestModuleWithPrereleaseDep", "PrereleaseModule" -SkipDependencyCheck -ErrorAction SilentlyContinue } @@ -40,9 +40,9 @@ Describe 'Test Install-PSResource for V2 Server scenarios' -tags 'CI' { } $testCases = [array]( - @{Name="*"; ErrorId="NameContainsWildcard"}, - @{Name="Test_Module*"; ErrorId="NameContainsWildcard"}, - @{Name="Test?Module","Test[Module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + @{Name = "*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test_Module*"; ErrorId = "NameContainsWildcard" }, + @{Name = "Test?Module", "Test[Module"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } ) It "Should not install resource with wildcard in name" -TestCases $testCases { @@ -122,8 +122,7 @@ Describe 'Test Install-PSResource for V2 Server scenarios' -tags 'CI' { $Version = "(1.0.0.0)" try { Install-PSResource -Name $testModuleName -Version $Version -Repository $PSGalleryName -TrustRepository -ErrorAction SilentlyContinue - } - catch { + } catch { } $Error[0].FullyQualifiedErrorId | Should -Be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource" diff --git a/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 index 49397859c..f9d4d9582 100644 --- a/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceV3Server.Tests.ps1 @@ -28,7 +28,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { AfterEach { Uninstall-PSResource 'test_module', 'test_module2', 'test_script', 'TestModule99', 'test_module_withlicense', 'TestFindModule', 'PackageManagement', ` - 'TestModuleWithDependencyE', 'TestModuleWithDependencyC', 'TestModuleWithDependencyB', 'TestModuleWithDependencyD' -SkipDependencyCheck -ErrorAction SilentlyContinue + 'TestModuleWithDependencyE', 'TestModuleWithDependencyC', 'TestModuleWithDependencyB', 'TestModuleWithDependencyD' -SkipDependencyCheck -ErrorAction SilentlyContinue } AfterAll { @@ -36,9 +36,9 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { } $testCases = [hashtable[]]( - @{Name='*'; ErrorId='NameContainsWildcard'}, - @{Name='Test_Module*'; ErrorId='NameContainsWildcard'}, - @{Name='Test?Module','Test[Module'; ErrorId='ErrorFilteringNamesForUnsupportedWildcards'} + @{Name = '*'; ErrorId = 'NameContainsWildcard' }, + @{Name = 'Test_Module*'; ErrorId = 'NameContainsWildcard' }, + @{Name = 'Test?Module', 'Test[Module'; ErrorId = 'ErrorFilteringNamesForUnsupportedWildcards' } ) It 'Should not install resource with wildcard in name' -TestCases $testCases { @@ -121,8 +121,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $Version = '(1.0.0.0)' try { Install-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName -TrustRepository -ErrorAction SilentlyContinue - } - catch { + } catch { } $Error[0].FullyQualifiedErrorId | Should -Be 'IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource' @@ -378,7 +377,7 @@ Describe 'Test Install-PSResource for V3Server scenarios' -tags 'CI' { $res3.Name | Should -Be 'testModule99' $res3.Version | Should -Be '0.0.93' } - + It "Install module and its dependencies" { $res = Install-PSResource 'TestModuleWithDependencyE' -Repository $NuGetGalleryName -TrustRepository -PassThru $res.Length | Should -Be 4 diff --git a/test/PSCredentialInfo.Tests.ps1 b/test/PSCredentialInfo.Tests.ps1 index 75c956d4f..3170d0779 100644 --- a/test/PSCredentialInfo.Tests.ps1 +++ b/test/PSCredentialInfo.Tests.ps1 @@ -27,7 +27,7 @@ Describe "Create PSCredentialInfo with VaultName, SecretName, and Credential" -t It "Creates PSCredentialInfo successfully if Credential is null" { $randomSecret = [System.IO.Path]::GetRandomFileName() $credentialInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret) - + $credentialInfo.VaultName | Should -Be "testvault" $credentialInfo.SecretName | Should -Be $randomSecret } @@ -48,7 +48,7 @@ Describe "Create PSCredentialInfo with VaultName, SecretName, and Credential" -t $credential = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString $randomPassword -AsPlainText -Force)) $hash = @{ "VaultName" = "testvault" ; "SecretName" = $randomSecret ; "Credential" = $credential } $credentialInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ($hash) - + $credentialInfo.VaultName | Should -Be "testvault" $credentialInfo.SecretName | Should -Be $randomSecret } @@ -70,7 +70,7 @@ Describe "Create PSCredentialInfo from a PSObject" -tags 'CI' { It "Creates PSCredentialInfo successfully from PSObject with VaultName and SecretName" { $randomSecret = [System.IO.Path]::GetRandomFileName() $properties = [PSCustomObject]@{ - VaultName = "testvault" + VaultName = "testvault" SecretName = $randomSecret } @@ -86,7 +86,7 @@ Describe "Create PSCredentialInfo from a PSObject" -tags 'CI' { $credential = New-Object System.Management.Automation.PSCredential ("username", (ConvertTo-SecureString $randomPassword -AsPlainText -Force)) $properties = [PSCustomObject]@{ - VaultName = "testvault" + VaultName = "testvault" SecretName = $randomSecret Credential = [PSCredential] $credential } @@ -98,13 +98,13 @@ Describe "Create PSCredentialInfo from a PSObject" -tags 'CI' { $credentialInfo.Credential.UserName | Should -Be "username" $credentialInfo.Credential.GetNetworkCredential().Password | Should -Be $randomPassword } - + It "Creates PSCredentialInfo successfully from PSObject with VaultName, SecretName and string Credential" { $randomSecret = [System.IO.Path]::GetRandomFileName() $randomPassword = [System.IO.Path]::GetRandomFileName() $properties = [PSCustomObject]@{ - VaultName = "testvault" + VaultName = "testvault" SecretName = $randomSecret Credential = $randomPassword } @@ -122,7 +122,7 @@ Describe "Create PSCredentialInfo from a PSObject" -tags 'CI' { $secureString = ConvertTo-SecureString $randomPassword -AsPlainText -Force $properties = [PSCustomObject]@{ - VaultName = "testvault" + VaultName = "testvault" SecretName = $randomSecret Credential = $secureString } diff --git a/test/PSGetTestUtils.psm1 b/test/PSGetTestUtils.psm1 index 6a384c17c..b8c2d7d0c 100644 --- a/test/PSGetTestUtils.psm1 +++ b/test/PSGetTestUtils.psm1 @@ -22,53 +22,36 @@ $script:PSGalleryLocation = 'https://www.powershellgallery.com/api/v2' $script:NuGetGalleryName = 'NuGetGallery' $script:NuGetGalleryLocation = 'https://api.nuget.org/v3/index.json' -if($script:IsInbox) -{ +if ($script:IsInbox) { $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell" -} -elseif($script:IsCoreCLR){ - if($script:IsWindows) { +} elseif ($script:IsCoreCLR) { + if ($script:IsWindows) { $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath 'PowerShell' - } - else { + } else { $script:ProgramFilesPSPath = Split-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('SHARED_MODULES')) -Parent } } -try -{ +try { $script:MyDocumentsFolderPath = [Environment]::GetFolderPath("MyDocuments") -} -catch -{ +} catch { $script:MyDocumentsFolderPath = $null } -if($script:IsInbox) -{ - $script:MyDocumentsPSPath = if($script:MyDocumentsFolderPath) - { - Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath "WindowsPowerShell" - } - else - { - Microsoft.PowerShell.Management\Join-Path -Path $env:USERPROFILE -ChildPath "Documents\WindowsPowerShell" - } -} -elseif($script:IsCoreCLR) { - if($script:IsWindows) - { - $script:MyDocumentsPSPath = if($script:MyDocumentsFolderPath) - { +if ($script:IsInbox) { + $script:MyDocumentsPSPath = if ($script:MyDocumentsFolderPath) { + Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath "WindowsPowerShell" + } else { + Microsoft.PowerShell.Management\Join-Path -Path $env:USERPROFILE -ChildPath "Documents\WindowsPowerShell" + } +} elseif ($script:IsCoreCLR) { + if ($script:IsWindows) { + $script:MyDocumentsPSPath = if ($script:MyDocumentsFolderPath) { Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath 'PowerShell' - } - else - { + } else { Microsoft.PowerShell.Management\Join-Path -Path $HOME -ChildPath "Documents\PowerShell" } - } - else - { + } else { $script:MyDocumentsPSPath = Split-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('USER_MODULES')) -Parent } } @@ -79,7 +62,7 @@ $script:ProgramFilesScriptsPath = Microsoft.PowerShell.Management\Join-Path -Pat $script:MyDocumentsScriptsPath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsPSPath -ChildPath 'Scripts' $script:TempPath = [System.IO.Path]::GetTempPath() -if($script:IsWindows) { +if ($script:IsWindows) { $script:PSGetProgramDataPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramData -ChildPath 'Microsoft\Windows\PowerShell\PSResourceGet\' $script:PSGetAppLocalPath = Microsoft.PowerShell.Management\Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\Windows\PowerShell\PSResourceGet\' } else { @@ -135,18 +118,15 @@ function Get-PSGetLocalAppDataPath { return $script:PSGetAppLocalPath } -function Get-NuGetGalleryName -{ +function Get-NuGetGalleryName { return $script:NuGetGalleryName } -function Get-NuGetGalleryLocation -{ +function Get-NuGetGalleryLocation { return $script:NuGetGalleryLocation } -function Get-PSGalleryName -{ +function Get-PSGalleryName { return $script:PSGalleryName } @@ -158,8 +138,7 @@ function Get-NewTestDirs { [string[]] $listOfPaths ) - foreach($path in $listOfPaths) - { + foreach ($path in $listOfPaths) { $null = New-Item -Path $path -ItemType Directory } } @@ -169,10 +148,8 @@ function Get-RemoveTestDirs { [string[]] $listOfPaths ) - foreach($path in $listOfPaths) - { - if(Test-Path -Path $path) - { + foreach ($path in $listOfPaths) { + if (Test-Path -Path $path) { Remove-Item -Path $path -Force -ErrorAction Ignore } } @@ -232,41 +209,41 @@ function Register-LocalRepos { $repoUriAddress = Join-Path -Path $TestDrive -ChildPath "testdir" $null = New-Item $repoUriAddress -ItemType Directory -Force $localRepoParams = @{ - Name = "psgettestlocal" - Uri = $repoUriAddress + Name = "psgettestlocal" + Uri = $repoUriAddress Priority = 40 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @localRepoParams $repoUriAddress2 = Join-Path -Path $TestDrive -ChildPath "testdir2" $null = New-Item $repoUriAddress2 -ItemType Directory -Force $localRepoParams2 = @{ - Name = "psgettestlocal2" - Uri = $repoUriAddress2 + Name = "psgettestlocal2" + Uri = $repoUriAddress2 Priority = 50 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @localRepoParams2 - # Both actually point to the same paths as the purely localpath repository, simplifying logistics - $repoUriAddress3 = Join-Path -Path $TestDrive -ChildPath "testdir" + # Both actually point to the same paths as the purely localpath repository, simplifying logistics + $repoUriAddress3 = Join-Path -Path $TestDrive -ChildPath "testdir" $path3 = Get-Item $repoUriAddress3 $localRepoParams = @{ - Name = "psgettestlocal3" - Uri = $path3.FullName -Replace '^(.):', '\\localhost\$1$' + Name = "psgettestlocal3" + Uri = $path3.FullName -Replace '^(.):', '\\localhost\$1$' Priority = 60 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @localRepoParams $repoUriAddress4 = Join-Path -Path $TestDrive -ChildPath "testdir2" $path4 = Get-Item $repoUriAddress4 $localRepoParams2 = @{ - Name = "psgettestlocal4" - Uri = $path4.FullName -Replace '^(.):', '\\localhost\$1$' + Name = "psgettestlocal4" + Uri = $path4.FullName -Replace '^(.):', '\\localhost\$1$' Priority = 70 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @localRepoParams2 @@ -284,10 +261,10 @@ function Register-LocalTestNupkgsRepo { $repoUriAddress = $testNupkgsFolderPath $localRepoParams = @{ - Name = "localNupkgRepo" - Uri = $repoUriAddress + Name = "localNupkgRepo" + Uri = $repoUriAddress Priority = 70 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @localRepoParams @@ -295,10 +272,10 @@ function Register-LocalTestNupkgsRepo { function Register-PSGallery { $PSGalleryRepoParams = @{ - Name = $script:PSGalleryName - Uri = $script:PSGalleryLocation + Name = $script:PSGalleryName + Uri = $script:PSGalleryLocation Priority = 1 - Trusted = $false + Trusted = $false } Register-PSResourceRepository @PSGalleryRepoParams @@ -306,29 +283,27 @@ function Register-PSGallery { } function Unregister-LocalRepos { - if(Get-PSResourceRepository -Name "psgettestlocal"){ + if (Get-PSResourceRepository -Name "psgettestlocal") { Unregister-PSResourceRepository -Name "psgettestlocal" } - if(Get-PSResourceRepository -Name "psgettestlocal2"){ + if (Get-PSResourceRepository -Name "psgettestlocal2") { Unregister-PSResourceRepository -Name "psgettestlocal2" } - if(Get-PSResourceRepository -Name "psgettestlocal3"){ + if (Get-PSResourceRepository -Name "psgettestlocal3") { Unregister-PSResourceRepository -Name "psgettestlocal3" } - if(Get-PSResourceRepository -Name "psgettestlocal4"){ + if (Get-PSResourceRepository -Name "psgettestlocal4") { Unregister-PSResourceRepository -Name "psgettestlocal4" } } -function Get-TestDriveSetUp -{ +function Get-TestDriveSetUp { $testResourcesFolder = Join-Path $TestDrive -ChildPath "TestLocalDirectory" $script:testIndividualResourceFolder = Join-Path -Path $testResourcesFolder -ChildPath "PSGet_$(Get-Random)" $null = New-Item -Path $testIndividualResourceFolder -ItemType Directory -Force } -function Get-RoleCapabilityResourcePublishedToLocalRepoTestDrive -{ +function Get-RoleCapabilityResourcePublishedToLocalRepoTestDrive { Param( [string] $roleCapName @@ -347,8 +322,7 @@ function Get-RoleCapabilityResourcePublishedToLocalRepoTestDrive Publish-PSResource -Path $publishModuleBase -Repository psgettestlocal } -function Get-DSCResourcePublishedToLocalRepoTestDrive -{ +function Get-DSCResourcePublishedToLocalRepoTestDrive { Param( [string] $dscName @@ -366,8 +340,7 @@ function Get-DSCResourcePublishedToLocalRepoTestDrive Publish-PSResource -Path $publishModuleBase -Repository psgettestlocal } -function Get-ScriptResourcePublishedToLocalRepoTestDrive -{ +function Get-ScriptResourcePublishedToLocalRepoTestDrive { Param( [string] $scriptName, @@ -384,26 +357,25 @@ function Get-ScriptResourcePublishedToLocalRepoTestDrive $null = New-Item -Path $scriptFilePath -ItemType File -Force $params = @{ - Version = $scriptVersion - GUID = [guid]::NewGuid() - Author = 'Jane' - CompanyName = 'Microsoft Corporation' - Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' - Description = "Description for the $scriptName script" - LicenseUri = "https://$scriptName.com/license" - IconUri = "https://$scriptName.com/icon" - ProjectUri = "https://$scriptName.com" - Tags = @('Tag1','Tag2', "Tag-$scriptName-$scriptVersion") - ReleaseNotes = "$scriptName release notes" - } + Version = $scriptVersion + GUID = [guid]::NewGuid() + Author = 'Jane' + CompanyName = 'Microsoft Corporation' + Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' + Description = "Description for the $scriptName script" + LicenseUri = "https://$scriptName.com/license" + IconUri = "https://$scriptName.com/icon" + ProjectUri = "https://$scriptName.com" + Tags = @('Tag1', 'Tag2', "Tag-$scriptName-$scriptVersion") + ReleaseNotes = "$scriptName release notes" + } $scriptMetadata = Create-PSScriptMetadata @params Set-Content -Path $scriptFilePath -Value $scriptMetadata Publish-PSResource -Path $scriptFilePath -Repository $scriptRepoName } -function Get-CommandResourcePublishedToLocalRepoTestDrive -{ +function Get-CommandResourcePublishedToLocalRepoTestDrive { Param( [string] $cmdName @@ -420,8 +392,7 @@ function Get-CommandResourcePublishedToLocalRepoTestDrive Publish-PSResource -Path $publishModuleBase -Repository psgettestlocal } -function Get-ModuleResourcePublishedToLocalRepoTestDrive -{ +function Get-ModuleResourcePublishedToLocalRepoTestDrive { Param( [string] $moduleName, @@ -441,15 +412,13 @@ function Get-ModuleResourcePublishedToLocalRepoTestDrive Publish-PSResource -Path $publishModuleBase -Repository $repoName } -function Create-TagsStringEntry -{ +function Create-TagsStringEntry { Param( [string[]] $tags ) - if (!$tags) - { + if (!$tags) { return "" } @@ -457,8 +426,7 @@ function Create-TagsStringEntry return $tagsString } -function New-TestModule -{ +function New-TestModule { Param( [string] $path = "$TestDrive", @@ -498,8 +466,7 @@ function New-TestModule $null = New-Item -Path $modulePath -ItemType Directory -Force $tagsEntry = Create-TagsStringEntry -tags $tags $prereleaseEntry = "" - if ($prereleaseLabel) - { + if ($prereleaseLabel) { $prereleaseEntry = "Prerelease = '{0}'" -f $prereleaseLabel } @@ -525,8 +492,7 @@ function New-TestModule Publish-PSResource -Path $modulePath -Repository $repoName } -function Get-ModuleResourcePublishedToLocalRepoTestDrive -{ +function Get-ModuleResourcePublishedToLocalRepoTestDrive { Param( [string] $moduleName, @@ -550,25 +516,17 @@ function Get-ModuleResourcePublishedToLocalRepoTestDrive $null = New-Item -Path $publishModuleBase -ItemType Directory -Force $version = $packageVersion - if (!$tags -or ($tags.Count -eq 0)) - { - if (!$prereleaseLabel) - { + if (!$tags -or ($tags.Count -eq 0)) { + if (!$prereleaseLabel) { New-ModuleManifest -Path (Join-Path -Path $publishModuleBase -ChildPath "$publishModuleName.psd1") -ModuleVersion $version -Description "$publishModuleName module" - } - else - { + } else { New-ModuleManifest -Path (Join-Path -Path $publishModuleBase -ChildPath "$publishModuleName.psd1") -ModuleVersion $version -Prerelease $prereleaseLabel -Description "$publishModuleName module" } - } - else { + } else { # tags is not null or is empty - if (!$prereleaseLabel) - { + if (!$prereleaseLabel) { New-ModuleManifest -Path (Join-Path -Path $publishModuleBase -ChildPath "$publishModuleName.psd1") -ModuleVersion $version -Description "$publishModuleName module" -Tags $tags - } - else - { + } else { New-ModuleManifest -Path (Join-Path -Path $publishModuleBase -ChildPath "$publishModuleName.psd1") -ModuleVersion $version -Prerelease $prereleaseLabel -Description "$publishModuleName module" -Tags $tags } } @@ -576,24 +534,21 @@ function Get-ModuleResourcePublishedToLocalRepoTestDrive Publish-PSResource -Path $publishModuleBase -Repository $repoName } -function RemoveItem -{ +function RemoveItem { Param( [string] $path ) - if($path -and (Test-Path $path)) - { + if ($path -and (Test-Path $path)) { Remove-Item $path -Force -Recurse -ErrorAction SilentlyContinue } } -function Create-PSScriptMetadata -{ +function Create-PSScriptMetadata { [OutputType([String])] - [CmdletBinding(PositionalBinding=$false, - SupportsShouldProcess=$true)] + [CmdletBinding(PositionalBinding = $false, + SupportsShouldProcess = $true)] Param ( @@ -656,13 +611,12 @@ function Create-PSScriptMetadata [string[]] $ReleaseNotes, - [Parameter()] + [Parameter()] [string] $PrivateData ) - Process - { + Process { $PSScriptInfoString = @" <#PSScriptInfo @@ -714,8 +668,7 @@ Checks that provided PSGetInfo object contents match the expected data from the test information file: PSGetModuleInfo.xml #> -function CheckForExpectedPSGetInfo -{ +function CheckForExpectedPSGetInfo { param ($psGetInfo) $psGetInfo.AdditionalMetadata.Keys | Should -HaveCount 22 @@ -768,8 +721,7 @@ function CheckForExpectedPSGetInfo $psGetInfo.Version | Should -Be "1.1.0" } -function Set-TestACRRepositories -{ +function Set-TestACRRepositories { Param( [string[]] $repositoryNames @@ -779,8 +731,7 @@ function Set-TestACRRepositories $acrRepositoryNamesFilePath = Join-Path -Path $acrRepositoryNamesFolder -ChildPath 'ACRTestRepositoryNames.txt' $fileExists = Test-Path -Path $acrRepositoryNamesFilePath - if ($fileExists) - { + if ($fileExists) { $repositoryNames | Out-File -FilePath $acrRepositoryNamesFilePath } } diff --git a/test/PSScriptFileInfoTests/GetPSScriptFileInfo.Tests.ps1 b/test/PSScriptFileInfoTests/GetPSScriptFileInfo.Tests.ps1 index 9e46e5000..9a331a212 100644 --- a/test/PSScriptFileInfoTests/GetPSScriptFileInfo.Tests.ps1 +++ b/test/PSScriptFileInfoTests/GetPSScriptFileInfo.Tests.ps1 @@ -91,22 +91,22 @@ Describe "Test Get-PSScriptFileInfo" -tags 'CI' { $foundExternalScriptDependencies = $res.ScriptMetadataComment.ExternalScriptDependencies $foundTags | Should -Be @("tag1", "tag2") - foreach($tag in $foundTags) { + foreach ($tag in $foundTags) { $tag | Should -Not -Contain "," } $foundExternalModuleDependencies | Should -Be @("Storage", "ActiveDirectory") - foreach($modDep in $foundExternalModuleDependencies) { + foreach ($modDep in $foundExternalModuleDependencies) { $modDep | Should -Not -Contain "," } $foundRequiredScripts | Should -Be @("Script1", "Script2") - foreach($reqScript in $foundRequiredScripts) { + foreach ($reqScript in $foundRequiredScripts) { $modDep | Should -Not -Contain "," } $foundExternalScriptDependencies | Should -Be @("ExtScript1", "ExtScript2") - foreach($scriptDep in $foundExternalScriptDependencies) { + foreach ($scriptDep in $foundExternalScriptDependencies) { $modDep | Should -Not -Contain "," } } diff --git a/test/PSScriptFileInfoTests/NewPSScriptFile.Tests.ps1 b/test/PSScriptFileInfoTests/NewPSScriptFile.Tests.ps1 index f45ce44d0..805bf0239 100644 --- a/test/PSScriptFileInfoTests/NewPSScriptFile.Tests.ps1 +++ b/test/PSScriptFileInfoTests/NewPSScriptFile.Tests.ps1 @@ -15,13 +15,12 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $script:testScriptFilePath = Join-Path -Path $tmpDir1Path -ChildPath "$script:PSScriptInfoName.ps1" } AfterEach { - if (Test-Path -Path $script:testScriptFilePath) - { + if (Test-Path -Path $script:testScriptFilePath) { Remove-Item $script:testScriptFilePath } } - It "Create .ps1 file with minimal required fields" { + It "Create .ps1 file with minimal required fields" { $description = "Test description" New-PSScriptFileInfo -Path $script:testScriptFilePath -Description $description Test-PSScriptFileInfo -Path $script:testScriptFilePath | Should -BeTrue @@ -39,7 +38,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { } It "Create new .ps1 given Version parameter" { - $version = "2.0.0.0" + $version = "2.0.0.0" $description = "Test description" New-PSScriptFileInfo -Path $script:testScriptFilePath -Version $version -Description $description @@ -63,7 +62,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { } It "Create new .ps1 given Author parameter" { - $author = "Test Author" + $author = "Test Author" $description = "Test description" New-PSScriptFileInfo -Path $script:testScriptFilePath -Author $author -Description $description @@ -86,7 +85,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { } It "Create new .ps1 given CompanyName parameter" { - $companyName = "Microsoft" + $companyName = "Microsoft" $description = "Test description" New-PSScriptFileInfo -Path $script:testScriptFilePath -CompanyName $companyName -Description $description @@ -98,7 +97,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { } It "Create new .ps1 given Copyright parameter" { - $copyright = "(c) Test Corporation" + $copyright = "(c) Test Corporation" $description = "Test description" New-PSScriptFileInfo -Path $script:testScriptFilePath -Copyright $copyright -Description $description @@ -112,11 +111,11 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { It "Create new .ps1 given RequiredModules parameter" { $requiredModuleName = 'PackageManagement' $requiredModuleVersion = '1.0.0.0' - $RequiredModules = @(@{ModuleName = $requiredModuleName; ModuleVersion = $requiredModuleVersion }) + $RequiredModules = @(@{ModuleName = $requiredModuleName; ModuleVersion = $requiredModuleVersion }) - $description = "Test description" + $description = "Test description" - New-PSScriptFileInfo -Path $script:testScriptFilePath -RequiredModules $RequiredModules -Description $Description + New-PSScriptFileInfo -Path $script:testScriptFilePath -RequiredModules $RequiredModules -Description $Description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -129,7 +128,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $description = "Test Description" $releaseNotes = "Release notes for script." - New-PSScriptFileInfo -Path $script:testScriptFilePath -ReleaseNotes $releaseNotes -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -ReleaseNotes $releaseNotes -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -142,7 +141,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $tag1 = "tag1" $tag2 = "tag2" - New-PSScriptFileInfo -Path $script:testScriptFilePath -Tags $tag1, $tag2 -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -Tags $tag1, $tag2 -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -156,7 +155,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $tag1 = "tag1" $tag2 = "tag2" - New-PSScriptFileInfo -Path $script:testScriptFilePath -Tag $tag1, $tag2 -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -Tag $tag1, $tag2 -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -169,7 +168,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $description = "Test Description" $projectUri = "https://www.testprojecturi.com/" - New-PSScriptFileInfo -Path $script:testScriptFilePath -ProjectUri $projectUri -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -ProjectUri $projectUri -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -181,7 +180,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $description = "Test Description" $licenseUri = "https://www.testlicenseuri.com/" - New-PSScriptFileInfo -Path $script:testScriptFilePath -LicenseUri $licenseUri -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -LicenseUri $licenseUri -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -193,7 +192,7 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { $description = "Test Description" $iconUri = "https://www.testiconuri.com/" - New-PSScriptFileInfo -Path $script:testScriptFilePath -IconUri $iconUri -Description $description + New-PSScriptFileInfo -Path $script:testScriptFilePath -IconUri $iconUri -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw @@ -245,12 +244,12 @@ Describe "Test New-PSScriptFileInfo" -tags 'CI' { It "Create new .ps1 given PrivateData parameter" { $description = "Test Description" - $privateData = @{"PrivateDataEntry1" = "PrivateDataValue1"} - New-PSScriptFileInfo -Path $script:testScriptFilePath -PrivateData $privateData -Description $description + $privateData = @{"PrivateDataEntry1" = "PrivateDataValue1" } + New-PSScriptFileInfo -Path $script:testScriptFilePath -PrivateData $privateData -Description $description Test-Path -Path $script:testScriptFilePath | Should -BeTrue $results = Get-Content -Path $script:testScriptFilePath -Raw $results.Contains($privateData) | Should -BeTrue $results -like "*.PRIVATEDATA*$privateData*" | Should -BeTrue } -} \ No newline at end of file +} diff --git a/test/PSScriptFileInfoTests/UpdatePSScriptFileInfo.Tests.ps1 b/test/PSScriptFileInfoTests/UpdatePSScriptFileInfo.Tests.ps1 index 96776db3d..82ca926c0 100644 --- a/test/PSScriptFileInfoTests/UpdatePSScriptFileInfo.Tests.ps1 +++ b/test/PSScriptFileInfoTests/UpdatePSScriptFileInfo.Tests.ps1 @@ -29,8 +29,7 @@ Describe "Test Update-PSScriptFileInfo" -tags 'CI' { } AfterEach { - if (Test-Path -Path $script:testScriptFilePath) - { + if (Test-Path -Path $script:testScriptFilePath) { Remove-Item $script:testScriptFilePath } } @@ -170,7 +169,7 @@ Describe "Test Update-PSScriptFileInfo" -tags 'CI' { It "update script file ExternalModuleDependencies property" { $externalModuleDep1 = "ExternalModuleDep1" $externalModuleDep2 = "ExternalModuleDep2" - Update-PSScriptFileInfo -Path $script:testScriptFilePath -ExternalModuleDependencies $externalModuleDep1,$externalModuleDep2 + Update-PSScriptFileInfo -Path $script:testScriptFilePath -ExternalModuleDependencies $externalModuleDep1, $externalModuleDep2 Test-PSScriptFileInfo $script:testScriptFilePath | Should -Be $true Test-Path -Path $script:testScriptFilePath | Should -BeTrue @@ -183,7 +182,7 @@ Describe "Test Update-PSScriptFileInfo" -tags 'CI' { It "update script file ExternalScriptDependencies property" { $externalScriptDep1 = "ExternalScriptDep1" $externalScriptDep2 = "ExternalScriptDep2" - Update-PSScriptFileInfo -Path $script:testScriptFilePath -ExternalScriptDependencies $externalScriptDep1,$externalScriptDep2 + Update-PSScriptFileInfo -Path $script:testScriptFilePath -ExternalScriptDependencies $externalScriptDep1, $externalScriptDep2 Test-PSScriptFileInfo $script:testScriptFilePath | Should -Be $true Test-Path -Path $script:testScriptFilePath | Should -BeTrue @@ -249,10 +248,10 @@ Describe "Test Update-PSScriptFileInfo" -tags 'CI' { } It "update script file RequiredModules property" { - $hashtable1 = @{ModuleName = "RequiredModule1"} - $hashtable2 = @{ModuleName = "RequiredModule2"; ModuleVersion = "1.0.0.0"} - $hashtable3 = @{ModuleName = "RequiredModule3"; RequiredVersion = "2.5.0.0"} - $hashtable4 = @{ModuleName = "RequiredModule4"; ModuleVersion = "1.1.0.0"; MaximumVersion = "2.0.0.0"} + $hashtable1 = @{ModuleName = "RequiredModule1" } + $hashtable2 = @{ModuleName = "RequiredModule2"; ModuleVersion = "1.0.0.0" } + $hashtable3 = @{ModuleName = "RequiredModule3"; RequiredVersion = "2.5.0.0" } + $hashtable4 = @{ModuleName = "RequiredModule4"; ModuleVersion = "1.1.0.0"; MaximumVersion = "2.0.0.0" } $requiredModules = $hashtable1, $hashtable2, $hashtable3, $hashtable4 Update-PSScriptFileInfo -Path $script:testScriptFilePath -RequiredModules $requiredModules diff --git a/test/PublishPSResourceTests/CompressPSResource.Tests.ps1 b/test/PublishPSResourceTests/CompressPSResource.Tests.ps1 index 28f74a742..d37a8da09 100644 --- a/test/PublishPSResourceTests/CompressPSResource.Tests.ps1 +++ b/test/PublishPSResourceTests/CompressPSResource.Tests.ps1 @@ -6,8 +6,7 @@ Import-Module $modPath -Force -Verbose $testDir = (get-item $psscriptroot).parent.FullName -function CreateTestModule -{ +function CreateTestModule { param ( [string] $Path = "$TestDrive", [string] $ModuleName = 'TestModule' @@ -42,8 +41,7 @@ function CreateTestModule '@ | Out-File -FilePath $moduleSrc } -function CompressExpandRetrieveNuspec -{ +function CompressExpandRetrieveNuspec { param( [string]$PublishModuleBase, [string]$PublishModuleName, @@ -96,17 +94,15 @@ Describe "Test Compress-PSResource" -tags 'CI' { $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" $script:PublishModuleName = "PSGetTestModule" $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { New-Item -Path $script:PublishModuleBase -ItemType Directory -Force } - $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' + $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' #Create dependency module $script:DependencyModuleName = "PackageManagement" $script:DependencyModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:DependencyModuleName - if(!(Test-Path $script:DependencyModuleBase)) - { + if (!(Test-Path $script:DependencyModuleBase)) { New-Item -Path $script:DependencyModuleBase -ItemType Directory -Force } @@ -116,8 +112,7 @@ Describe "Test Compress-PSResource" -tags 'CI' { #Create folder where we shall place all script files to be published for these tests $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath" - if(!(Test-Path $script:tmpScriptsFolderPath)) - { + if (!(Test-Path $script:tmpScriptsFolderPath)) { New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force } @@ -134,7 +129,7 @@ Describe "Test Compress-PSResource" -tags 'CI' { CreateTestModule -Path $TestDrive -ModuleName 'ModuleWithMissingRequiredModule' } AfterAll { - Get-RevertPSResourceRepositoryFile + Get-RevertPSResourceRepositoryFile } AfterEach { # Delete all contents of the repository without deleting the repository directory itself @@ -151,9 +146,9 @@ Describe "Test Compress-PSResource" -tags 'CI' { It "Compress-PSResource compresses a module into a nupkg and saves it to the DestinationPath" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" - + Compress-PSResource -Path $script:PublishModuleBase -DestinationPath $script:repositoryPath - + $expectedPath = Join-Path -Path $script:repositoryPath -ChildPath "$script:PublishModuleName.$version.nupkg" (Get-ChildItem $script:repositoryPath).FullName | Should -Be $expectedPath } @@ -179,7 +174,7 @@ Describe "Test Compress-PSResource" -tags 'CI' { # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $script:repositoryPath -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $script:repositoryPath -ChildPath "$script:PublishModuleName.$version.zip" - Rename-Item -Path $nupkgPath -NewName $zipPath + Rename-Item -Path $nupkgPath -NewName $zipPath $unzippedPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName" New-Item $unzippedPath -Itemtype directory -Force Expand-Archive -Path $zipPath -DestinationPath $unzippedPath @@ -193,18 +188,18 @@ Describe "Test Compress-PSResource" -tags 'CI' { $scriptVersion = "1.0.0" $params = @{ - Version = $scriptVersion - GUID = [guid]::NewGuid() - Author = 'Jane' - CompanyName = 'Microsoft Corporation' - Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' - Description = "Description for the $scriptName script" - LicenseUri = "https://$scriptName.com/license" - IconUri = "https://$scriptName.com/icon" - ProjectUri = "https://$scriptName.com" - Tags = @('Tag1','Tag2', "Tag-$scriptName-$scriptVersion") + Version = $scriptVersion + GUID = [guid]::NewGuid() + Author = 'Jane' + CompanyName = 'Microsoft Corporation' + Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' + Description = "Description for the $scriptName script" + LicenseUri = "https://$scriptName.com/license" + IconUri = "https://$scriptName.com/icon" + ProjectUri = "https://$scriptName.com" + Tags = @('Tag1', 'Tag2', "Tag-$scriptName-$scriptVersion") ReleaseNotes = "$scriptName release notes" - } + } $scriptPath = (Join-Path -Path $script:tmpScriptsFolderPath -ChildPath "$scriptName.ps1") New-PSScriptFileInfo @params -Path $scriptPath @@ -238,7 +233,7 @@ Describe "Test Compress-PSResource" -tags 'CI' { Remove-Item -Path $relativePath -Recurse -Force Remove-Item -Path $relativeDestination -Recurse -Force } - + It "Compress-PSResource -PassThru returns a FileInfo object with the correct path" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" @@ -396,20 +391,20 @@ Describe "Test Compress-PSResource" -tags 'CI' { } } -<# Test for Signing the nupkg. Signing doesn't work + <# Test for Signing the nupkg. Signing doesn't work It "Compressed Module is able to be signed with a certificate" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" Compress-PSResource -Path $script:PublishModuleBase -DestinationPath $script:repositoryPath2 - + $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath # create test cert # Create a self-signed certificate for code signing $testCert = New-SelfSignedCertificate -Subject "CN=NuGet Test Developer, OU=Use for testing purposes ONLY" -FriendlyName "NuGetTestDeveloper" -Type CodeSigning -KeyUsage DigitalSignature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256 -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -CertStoreLocation "Cert:\CurrentUser\My" - + # sign the nupkg $nupkgPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" Set-AuthenticodeSignature -FilePath $nupkgPath -Certificate $testCert diff --git a/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 index 84e941dfa..afdc1e449 100644 --- a/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 @@ -6,8 +6,7 @@ Import-Module $modPath -Force -Verbose $testDir = (get-item $psscriptroot).parent.FullName -function CreateTestModule -{ +function CreateTestModule { param ( [string] $Path = "$TestDrive", [string] $ModuleName = 'TestModule' @@ -63,17 +62,15 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" $script:PublishModuleName = "PSGetTestModule" $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { New-Item -Path $script:PublishModuleBase -ItemType Directory -Force } - $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' + $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' #Create dependency module $script:DependencyModuleName = "PackageManagement" $script:DependencyModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:DependencyModuleName - if(!(Test-Path $script:DependencyModuleBase)) - { + if (!(Test-Path $script:DependencyModuleBase)) { New-Item -Path $script:DependencyModuleBase -ItemType Directory -Force } @@ -83,8 +80,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { #Create folder where we shall place all script files to be published for these tests $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath" - if(!(Test-Path $script:tmpScriptsFolderPath)) - { + if (!(Test-Path $script:tmpScriptsFolderPath)) { New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force } @@ -101,7 +97,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { CreateTestModule -Path $TestDrive -ModuleName 'ModuleWithMissingRequiredModule' } AfterAll { - Get-RevertPSResourceRepositoryFile + Get-RevertPSResourceRepositoryFile } AfterEach { # Delete all contents of the repository without deleting the repository directory itself @@ -149,7 +145,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { (Get-ChildItem $script:repositoryPath).FullName | Should -Be $expectedPath } - #region Local Source Path + #region Local Source Path It "Publish a module with -Path and -Repository" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" @@ -205,9 +201,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath } - #endregion Local Source Path + #endregion Local Source Path - #region UNC Source Path + #region UNC Source Path It "Publish a module with -Path and -Repository, with the path pointing to a network share" { $version = "1.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBaseUNC -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" @@ -263,7 +259,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath } - #endregion UNC Source Path + #endregion UNC Source Path It "Publish a module with dependencies" { # Create dependency module @@ -291,7 +287,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $dependencyVersion = "2.0.0" New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" -RequiredModules @(@{ModuleName = 'PackageManagement'; ModuleVersion = '1.4.4' }) - {Publish-PSResource -Path $script:PublishModuleBase -ErrorAction Stop} | Should -Throw -ErrorId "DependencyNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $script:PublishModuleBase -ErrorAction Stop } | Should -Throw -ErrorId "DependencyNotFound,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with -SkipDependenciesCheck" { @@ -316,7 +312,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { # Must change .nupkg to .zip so that Expand-Archive can work on Windows PowerShell $nupkgPath = Join-Path -Path $script:repositoryPath -ChildPath "$script:PublishModuleName.$version.nupkg" $zipPath = Join-Path -Path $script:repositoryPath -ChildPath "$script:PublishModuleName.$version.zip" - Rename-Item -Path $nupkgPath -NewName $zipPath + Rename-Item -Path $nupkgPath -NewName $zipPath $unzippedPath = Join-Path -Path $TestDrive -ChildPath "$script:PublishModuleName" New-Item $unzippedPath -Itemtype directory -Force Expand-Archive -Path $zipPath -DestinationPath $unzippedPath @@ -331,7 +327,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { Compress-PSResource -Path $script:PublishModuleBase -DestinationPath $script:destinationPath $expectedPath = Join-Path -Path $script:destinationPath -ChildPath "$script:PublishModuleName.$version.nupkg" (Get-ChildItem $script:destinationPath).FullName | Should -Be $expectedPath - + # Pass the nupkg via -NupkgPath Publish-PSResource -NupkgPath $expectedPath -Repository $testRepository2 $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" @@ -475,7 +471,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $moduleName = "Pester" $moduleVersion = "5.5.0" Save-PSResource -Name $moduleName -Path $tmpRepoPath -Version $moduleVersion -Repository PSGallery -TrustRepository - $modulePath = Join-Path -Path $tmpRepoPath -ChildPath $moduleName + $modulePath = Join-Path -Path $tmpRepoPath -ChildPath $moduleName $moduleVersionPath = Join-Path -Path $modulePath -ChildPath $moduleVersion $moduleManifestPath = Join-path -Path $moduleVersionPath -ChildPath "$moduleName.psd1" Publish-PSResource -Path $moduleManifestPath -Repository $testRepository2 @@ -512,23 +508,23 @@ Describe "Test Publish-PSResource" -tags 'CI' { (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath } - It "publish a script locally"{ + It "publish a script locally" { $scriptName = "PSGetTestScript" $scriptVersion = "1.0.0" $params = @{ - Version = $scriptVersion - GUID = [guid]::NewGuid() - Author = 'Jane' - CompanyName = 'Microsoft Corporation' - Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' - Description = "Description for the $scriptName script" - LicenseUri = "https://$scriptName.com/license" - IconUri = "https://$scriptName.com/icon" - ProjectUri = "https://$scriptName.com" - Tags = @('Tag1','Tag2', "Tag-$scriptName-$scriptVersion") + Version = $scriptVersion + GUID = [guid]::NewGuid() + Author = 'Jane' + CompanyName = 'Microsoft Corporation' + Copyright = '(c) 2020 Microsoft Corporation. All rights reserved.' + Description = "Description for the $scriptName script" + LicenseUri = "https://$scriptName.com/license" + IconUri = "https://$scriptName.com/icon" + ProjectUri = "https://$scriptName.com" + Tags = @('Tag1', 'Tag2', "Tag-$scriptName-$scriptVersion") ReleaseNotes = "$scriptName release notes" - } + } $scriptPath = (Join-Path -Path $script:tmpScriptsFolderPath -ChildPath "$scriptName.ps1") New-PSScriptFileInfo @params -Path $scriptPath @@ -565,9 +561,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $scriptName = "test" $scriptVersion = "1.0.0" $scriptPath = Join-Path -Path $script:testScriptsFolderPath -ChildPath "$scriptName.ps1" - New-PSScriptFileInfo -Description 'test' -Version $scriptVersion -RequiredModules @{ModuleName='testModule'} -ExternalModuleDependencies 'testModule' -Path $scriptPath -Force + New-PSScriptFileInfo -Description 'test' -Version $scriptVersion -RequiredModules @{ModuleName = 'testModule' } -ExternalModuleDependencies 'testModule' -Path $scriptPath -Force - Publish-PSResource -Path $scriptPath + Publish-PSResource -Path $scriptPath $expectedPath = Join-Path -Path $script:repositoryPath -ChildPath "$scriptName.$scriptVersion.nupkg" (Get-ChildItem $script:repositoryPath).FullName | Should -Be $expectedPath @@ -642,14 +638,14 @@ Describe "Test Publish-PSResource" -tags 'CI' { $moduleName = "incorrectmoduleversion" $incorrectmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName - {Publish-PSResource -Path $incorrectmoduleversion -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $incorrectmoduleversion -ErrorAction Stop } | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with a dependency that has an invalid version format, should throw" { $moduleName = "incorrectdepmoduleversion" $incorrectdepmoduleversion = Join-Path -Path $script:testModulesFolderPath -ChildPath $moduleName - {Publish-PSResource -Path $incorrectdepmoduleversion -ErrorAction Stop} | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $incorrectdepmoduleversion -ErrorAction Stop } | Should -Throw -ErrorId "InvalidModuleManifest,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with using an invalid file path (path to .psm1), should throw" { @@ -657,7 +653,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $psm1Path = Join-Path -Path $script:PublishModuleBase -ChildPath $fileName $null = New-Item -Path $psm1Path -ItemType File -Force - {Publish-PSResource -Path $psm1Path -Repository $testRepository2 -ErrorAction Stop} | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $psm1Path -Repository $testRepository2 -ErrorAction Stop } | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Get definition for alias 'pbres'" { @@ -671,7 +667,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $DepPrereleaseLabel = "beta" $DepModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath $DepModuleName - New-TestModule -Path $DepModuleRoot -ModuleName $DepModuleName -RepoName $testRepository2 -PackageVersion $DepVersion -prereleaseLabel $DepPrereleaseLabel + New-TestModule -Path $DepModuleRoot -ModuleName $DepModuleName -RepoName $testRepository2 -PackageVersion $DepVersion -prereleaseLabel $DepPrereleaseLabel Install-PSResource -Name $DepModuleName -Repository $testRepository2 -TrustRepository -Prerelease $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$DepModuleName.$DepVersion-$DepPrereleaseLabel.nupkg" @@ -689,7 +685,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$ParentModuleName.$ParentVersion.nupkg" (Get-ChildItem $script:repositoryPath2).FullName | Should -Contain $expectedPath } -<# + <# It "Publish a module with required modules (both in string format and hashtable format)" { # look at functions in test utils for creating a module with prerelease $ModuleName = "ParentModule" @@ -712,7 +708,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-ModuleManifest -Path $ModuleManifestPath -ModuleVersion $ModuleVersion -Description "$ModuleName module" -RequiredModules @( @{ "ModuleName" = $ReqModule1Name; "ModuleVersion" = $ReqModule1Version }, $ReqModule2Name ) New-ModuleManifest -Path $ReqModule1ManifestPath -ModuleVersion $ReqModule1Version -Description "$ReqModule1Name module" New-ModuleManifest -Path $ReqModule2ManifestPath -Description "$ReqModule1Name module" - + Publish-PSResource -Path $ReqModule1ManifestPath -Repository $testRepository2 Publish-PSResource -Path $ReqModule2ManifestPath -Repository $testRepository2 diff --git a/test/PublishPSResourceTests/PublishPSResourceADOServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceADOServer.Tests.ps1 index e5984b7f3..22f91016b 100644 --- a/test/PublishPSResourceTests/PublishPSResourceADOServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceADOServer.Tests.ps1 @@ -6,8 +6,7 @@ Import-Module $modPath -Force -Verbose $testDir = (get-item $psscriptroot).parent.FullName -function CreateTestModule -{ +function CreateTestModule { param ( [string] $Path = "$TestDrive", [string] $ModuleName = 'TestModule' @@ -69,8 +68,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" $script:PublishModuleName = "PSGetTestModule" $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { New-Item -Path $script:PublishModuleBase -ItemType Directory -Force } @@ -79,7 +77,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { New-Item $script:destinationPath -ItemType directory -Force } AfterAll { - Get-RevertPSResourceRepositoryFile + Get-RevertPSResourceRepositoryFile } It "Should not publish module to ADO repository feed (public) when Credentials are incorrect" { diff --git a/test/PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1 index af57385a1..e43c60629 100644 --- a/test/PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1 @@ -4,8 +4,7 @@ $modPath = "$psscriptroot/../PSGetTestUtils.psm1" Import-Module $modPath -Force -Verbose -function CreateTestModule -{ +function CreateTestModule { param ( [string] $Path = "$TestDrive", [string] $ModuleName = 'temp-testmodule' @@ -51,12 +50,9 @@ Describe "Test Publish-PSResource" -tags 'CI' { $usingAzAuth = $env:USINGAZAUTH -eq 'true' - if ($usingAzAuth) - { + if ($usingAzAuth) { Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -Verbose - } - else - { + } else { $psCredInfo = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("SecretStore", "$env:TENANTID") Register-PSResourceRepository -Name $ACRRepoName -ApiVersion 'ContainerRegistry' -Uri $ACRRepoUri -CredentialInfo $psCredInfo -Verbose } @@ -65,11 +61,10 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:tmpModulesPath = Join-Path -Path $TestDrive -ChildPath "tmpModulesPath" $script:PublishModuleName = "temp-testmodule" + [System.Guid]::NewGuid(); $script:PublishModuleBase = Join-Path $script:tmpModulesPath -ChildPath $script:PublishModuleName - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { New-Item -Path $script:PublishModuleBase -ItemType Directory -Force } - $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' + $script:PublishModuleBaseUNC = $script:PublishModuleBase -Replace '^(.):', '\\localhost\$1$' # create names of other modules and scripts that will be referenced in test $script:ModuleWithoutRequiredModuleName = "temp-testmodulewithoutrequiredmodule-" + [System.Guid]::NewGuid() @@ -84,8 +79,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { #Create folder where we shall place all script files to be published for these tests $script:tmpScriptsFolderPath = Join-Path -Path $TestDrive -ChildPath "tmpScriptsPath" - if(!(Test-Path $script:tmpScriptsFolderPath)) - { + if (!(Test-Path $script:tmpScriptsFolderPath)) { $null = New-Item -Path $script:tmpScriptsFolderPath -ItemType Directory -Force } @@ -102,8 +96,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:testNupkgsFolderPath = Join-Path $script:testFilesFolderPath -ChildPath "testNupkgs" } AfterEach { - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { Remove-Item -Path $script:PublishModuleBase -Recurse -Force } } @@ -344,21 +337,21 @@ Describe "Test Publish-PSResource" -tags 'CI' { $results[0].Version | Should -Be $correctVersion } - It "Publish a script"{ + It "Publish a script" { $scriptVersion = "1.0.0" $params = @{ - Version = $scriptVersion - GUID = [guid]::NewGuid() - Author = 'Jane' - CompanyName = 'Microsoft Corporation' - Copyright = '(c) 2024 Microsoft Corporation. All rights reserved.' - Description = "Description for the $script:ScriptName script" - LicenseUri = "https://$script:ScriptName.com/license" - IconUri = "https://$script:ScriptName.com/icon" - ProjectUri = "https://$script:ScriptName.com" - Tags = @('Tag1','Tag2', "Tag-$script:ScriptName-$scriptVersion") + Version = $scriptVersion + GUID = [guid]::NewGuid() + Author = 'Jane' + CompanyName = 'Microsoft Corporation' + Copyright = '(c) 2024 Microsoft Corporation. All rights reserved.' + Description = "Description for the $script:ScriptName script" + LicenseUri = "https://$script:ScriptName.com/license" + IconUri = "https://$script:ScriptName.com/icon" + ProjectUri = "https://$script:ScriptName.com" + Tags = @('Tag1', 'Tag2', "Tag-$script:ScriptName-$scriptVersion") ReleaseNotes = "$script:ScriptName release notes" - } + } $scriptPath = (Join-Path -Path $script:tmpScriptsFolderPath -ChildPath "$script:ScriptName.ps1") New-PSScriptFileInfo @params -Path $scriptPath @@ -404,7 +397,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { It "Should publish a script with ExternalModuleDependencies that are not published" { $scriptVersion = "1.0.0" $scriptPath = Join-Path -Path $script:tmpScriptsFolderPath -ChildPath "$script:ScriptWithExternalDeps.ps1" - New-PSScriptFileInfo -Description 'test' -Version $scriptVersion -RequiredModules @{ModuleName='testModule'} -ExternalModuleDependencies 'testModule' -Path $scriptPath -Force + New-PSScriptFileInfo -Description 'test' -Version $scriptVersion -RequiredModules @{ModuleName = 'testModule' } -ExternalModuleDependencies 'testModule' -Path $scriptPath -Force Publish-PSResource -Path $scriptPath -Repository $ACRRepoName @@ -499,7 +492,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $psm1Path = Join-Path -Path $script:PublishModuleBase -ChildPath $fileName $null = New-Item -Path $psm1Path -ItemType File -Force - {Publish-PSResource -Path $psm1Path -Repository $ACRRepoName -ErrorAction Stop} | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" + { Publish-PSResource -Path $psm1Path -Repository $ACRRepoName -ErrorAction Stop } | Should -Throw -ErrorId "InvalidPublishPath,Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource" } It "Publish a module with -ModulePrefix" { diff --git a/test/ResourceRepositoryTests/GetPSResourceRepository.Tests.ps1 b/test/ResourceRepositoryTests/GetPSResourceRepository.Tests.ps1 index 58a654e70..fb9552294 100644 --- a/test/ResourceRepositoryTests/GetPSResourceRepository.Tests.ps1 +++ b/test/ResourceRepositoryTests/GetPSResourceRepository.Tests.ps1 @@ -48,7 +48,7 @@ Describe "Test Get-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName2 -Uri $tmpDir2Path Register-PSResourceRepository -Name "MyGallery" -Uri $tmpDir3Path - $res = Get-PSResourceRepository -Name "testReposit*","*Gallery" + $res = Get-PSResourceRepository -Name "testReposit*", "*Gallery" foreach ($entry in $res) { $entry.Name | Should -Match "testReposit|Gallery" } @@ -58,9 +58,9 @@ Describe "Test Get-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Register-PSResourceRepository -Name "MyGallery" -Uri $tmpDir2Path - $res = Get-PSResourceRepository -Name $TestRepoName1,"MyGallery" + $res = Get-PSResourceRepository -Name $TestRepoName1, "MyGallery" foreach ($entry in $res) { - $entry.Name | Should -BeIn $TestRepoName1,"MyGallery" + $entry.Name | Should -BeIn $TestRepoName1, "MyGallery" } } @@ -78,13 +78,13 @@ Describe "Test Get-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Register-PSResourceRepository -Name $TestRepoName2 -Uri $tmpDir2Path - $res = Get-PSResourceRepository -Name $TestRepoName1,$nonRegisteredRepoName,$TestRepoName2 -ErrorVariable err -ErrorAction SilentlyContinue + $res = Get-PSResourceRepository -Name $TestRepoName1, $nonRegisteredRepoName, $TestRepoName2 -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorGettingSpecifiedRepo,Microsoft.PowerShell.PSResourceGet.Cmdlets.GetPSResourceRepository" # should have successfully got the other valid/registered repositories with no error foreach ($entry in $res) { - $entry.Name | Should -BeIn $TestRepoName1,$TestRepoName2 + $entry.Name | Should -BeIn $TestRepoName1, $TestRepoName2 } } @@ -97,18 +97,18 @@ Describe "Test Get-PSResourceRepository" -tags 'CI' { # should have successfully got the other valid/registered repositories with no error foreach ($entry in $res) { - $entry.Name | Should -BeIn "localtestrepo1","localtestrepo2" + $entry.Name | Should -BeIn "localtestrepo1", "localtestrepo2" } } It "throw error and get no repositories when provided null Name" { # $errorMsg = "Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again." - {Get-PSResourceRepository -Name $null -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.GetPSResourceRepository" + { Get-PSResourceRepository -Name $null -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.GetPSResourceRepository" } It "throw error and get no repositories when provided empty string Name" { # $errorMsg = "Cannot validate argument on parameter 'Name'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again." - {Get-PSResourceRepository -Name "" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.GetPSResourceRepository" + { Get-PSResourceRepository -Name "" -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.GetPSResourceRepository" } It "find all repositories if no Name provided" { diff --git a/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 b/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 index fcaa9dcda..3fafa4489 100644 --- a/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 +++ b/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 @@ -26,7 +26,7 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { $randomSecret = [System.IO.Path]::GetRandomFileName() $randomPassword = [System.IO.Path]::GetRandomFileName() - + $credentialInfo1 = New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret) $secureString = ConvertTo-SecureString $randomPassword -AsPlainText -Force $credential = New-Object pscredential ("testusername", $secureString) @@ -104,10 +104,10 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } It "register repositories with -Repository parameter, all name parameter style repositories (RepositoriesParameterSet)" { - $hashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir1Path} - $hashtable2 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} - $hashtable3 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} - $hashtable4 = @{Name = $TestRepoName4; Uri = $tmpDir4Path; Trusted = $True; Priority = 30; CredentialInfo = (New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret))} + $hashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir1Path } + $hashtable2 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True } + $hashtable3 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20 } + $hashtable4 = @{Name = $TestRepoName4; Uri = $tmpDir4Path; Trusted = $True; Priority = 30; CredentialInfo = (New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret)) } $arrayOfHashtables = $hashtable1, $hashtable2, $hashtable3, $hashtable4 Register-PSResourceRepository -Repository $arrayOfHashtables @@ -137,7 +137,7 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { It "register repositories with -Repository parameter, psgallery style repository (RepositoriesParameterSet)" { Unregister-PSResourceRepository -Name $PSGalleryName - $hashtable1 = @{PSGallery = $True} + $hashtable1 = @{PSGallery = $True } Register-PSResourceRepository -Repository $hashtable1 $res = Get-PSResourceRepository -Name $PSGalleryName $res.Uri | Should -Be $PSGalleryUri @@ -147,11 +147,11 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { It "register repositories with -Repository parameter, name and psgallery parameter styles (RepositoriesParameterSet)" { Unregister-PSResourceRepository -Name $PSGalleryName - $hashtable1 = @{PSGallery = $True} - $hashtable2 = @{Name = $TestRepoName1; Uri = $tmpDir1Path} - $hashtable3 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} - $hashtable4 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} - $hashtable5 = @{Name = $TestRepoName4; Uri = $tmpDir4Path; Trusted = $True; Priority = 30; CredentialInfo = (New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret))} + $hashtable1 = @{PSGallery = $True } + $hashtable2 = @{Name = $TestRepoName1; Uri = $tmpDir1Path } + $hashtable3 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True } + $hashtable4 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20 } + $hashtable5 = @{Name = $TestRepoName4; Uri = $tmpDir4Path; Trusted = $True; Priority = 30; CredentialInfo = (New-Object Microsoft.PowerShell.PSResourceGet.UtilClasses.PSCredentialInfo ("testvault", $randomSecret)) } $arrayOfHashtables = $hashtable1, $hashtable2, $hashtable3, $hashtable4, $hashtable5 Register-PSResourceRepository -Repository $arrayOfHashtables @@ -186,42 +186,42 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } It "not register repository when Name is provided but Uri is not" { - {Register-PSResourceRepository -Name $TestRepoName1 -Uri "" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name $TestRepoName1 -Uri "" -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } It "not register repository when Name is empty but Uri is provided" { - {Register-PSResourceRepository -Name "" -Uri $tmpDir1Path -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name "" -Uri $tmpDir1Path -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } It "not register repository when Name is null but Uri is provided" { - {Register-PSResourceRepository -Name $null -Uri $tmpDir1Path -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name $null -Uri $tmpDir1Path -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } It "not register repository when Name is just whitespace but Uri is provided" { - {Register-PSResourceRepository -Name " " -Uri $tmpDir1Path -ErrorAction Stop} | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name " " -Uri $tmpDir1Path -ErrorAction Stop } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } It "not register PSGallery with NameParameterSet" { - {Register-PSResourceRepository -Name $PSGalleryName -Uri $PSGalleryUri -ErrorAction Stop} | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -Name $PSGalleryName -Uri $PSGalleryUri -ErrorAction Stop } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } # this error message comes from the parameter cmdlet tags (earliest point of detection) It "not register PSGallery when PSGallery parameter provided with Name, Uri or CredentialInfo" { - {Register-PSResourceRepository -PSGallery -Name $PSGalleryName -ErrorAction Stop} | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" - {Register-PSResourceRepository -PSGallery -Uri $PSGalleryUri -ErrorAction Stop} | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" - {Register-PSResourceRepository -PSGallery -CredentialInfo $credentialInfo1 -ErrorAction Stop} | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -PSGallery -Name $PSGalleryName -ErrorAction Stop } | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -PSGallery -Uri $PSGalleryUri -ErrorAction Stop } | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" + { Register-PSResourceRepository -PSGallery -CredentialInfo $credentialInfo1 -ErrorAction Stop } | Should -Throw -ErrorId "AmbiguousParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.RegisterPSResourceRepository" } - $testCases = @{Type = "Name key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; Name=$PSGalleryName}}, - @{Type = "Uri key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; Uri=$PSGalleryUri}}, - @{Type = "CredentialInfo key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; CredentialInfo = $credentialInfo1}} + $testCases = @{Type = "Name key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; Name = $PSGalleryName } }, + @{Type = "Uri key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; Uri = $PSGalleryUri } }, + @{Type = "CredentialInfo key specified with PSGallery key"; IncorrectHashTable = @{PSGallery = $True; CredentialInfo = $credentialInfo1 } } It "not register incorrectly formatted PSGallery type repo among correct ones when incorrect type is " -TestCases $testCases { param($Type, $IncorrectHashTable) - $correctHashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir1Path} - $correctHashtable2 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} - $correctHashtable3 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir1Path } + $correctHashtable2 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True } + $correctHashtable3 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20 } $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 Unregister-PSResourceRepository -Name $PSGalleryName @@ -240,10 +240,10 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } 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}; - $IncorrectHashTable = @{Uri = $tmpDir1Path}; + $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 @@ -265,10 +265,10 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } 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}; - $IncorrectHashTable = @{Name = $PSGalleryName; Uri = $tmpDir1Path}; + $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 @@ -290,10 +290,10 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } 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}; + $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 @@ -315,10 +315,10 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } 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"}; + $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 @@ -367,7 +367,7 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { $res.Name | Should -Be "localFileShareTestRepo" $res.Uri.LocalPath | Should -Contain "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" } - + 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 -ErrorAction SilentlyContinue } | Should -Throw @@ -376,9 +376,9 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { } It "should register a repository with a hashtable passed in as CredentialInfo" { - $hashtable = @{VaultName = "testvault"; SecretName = $randomSecret} + $hashtable = @{VaultName = "testvault"; SecretName = $randomSecret } - Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $hashtable + Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $hashtable $res = Get-PSResourceRepository -Name $TestRepoName1 $res.CredentialInfo.VaultName | Should -Be "testvault" @@ -386,7 +386,7 @@ Describe "Test Register-PSResourceRepository" -tags 'CI' { $res.CredentialInfo.Credential | Should -BeNullOrEmpty } - It "should register temp drive as a repository" -skip:(!$IsWindows) { + It "should register temp drive as a repository" -skip:(!$IsWindows) { Register-PSResourceRepository -Name "tempDriveRepo" -Uri "Temp:\" $res = Get-PSResourceRepository -Name "tempDriveRepo" diff --git a/test/ResourceRepositoryTests/SetPSResourceRepository.Tests.ps1 b/test/ResourceRepositoryTests/SetPSResourceRepository.Tests.ps1 index 4f1279b87..bc654be31 100644 --- a/test/ResourceRepositoryTests/SetPSResourceRepository.Tests.ps1 +++ b/test/ResourceRepositoryTests/SetPSResourceRepository.Tests.ps1 @@ -100,32 +100,41 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { It "not set repository and write error given just Name parameter" { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path - {Set-PSResourceRepository -Name $TestRepoName1 -ErrorAction Stop} | Should -Throw -ErrorId "SetRepositoryParameterBindingFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" + { Set-PSResourceRepository -Name $TestRepoName1 -ErrorAction Stop } | Should -Throw -ErrorId "SetRepositoryParameterBindingFailure,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" } - $testCases = @{Type = "contains *"; Name = "test*Repository"; ErrorId = "ErrorInNameParameterSet"}, - @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorInNameParameterSet"}, - @{Type = "is null"; Name = $null; ErrorId = "ParameterArgumentValidationError"} + $testCases = @{Type = "contains *"; Name = "test*Repository"; ErrorId = "ErrorInNameParameterSet" }, + @{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) Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path - {Set-PSResourceRepository -Name $Name -Priority 25 -ErrorAction Stop} | Should -Throw -ErrorId "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" + { Set-PSResourceRepository -Name $Name -Priority 25 -ErrorAction Stop } | Should -Throw -ErrorId "$ErrorId,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" } - $testCases2 = @{Type = "contains *"; Name = "test*Repository2"; ErrorId = "ErrorSettingRepository"}, - @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorSettingRepository"}, - @{Type = "is null"; Name = $null; ErrorId = "NullNameForRepositoriesParameterSetRepo"} + $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) Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Register-PSResourceRepository -Name $TestRepoName2 -Uri $tmpDir2Path - $hashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir3Path} - $hashtable2 = @{Name = $TestRepoName2; Priority = 25} - $incorrectHashTable = @{Name = $Name; Trusted = $True} + $hashtable1 = @{ + Name = $TestRepoName1 + Uri = $tmpDir3Path + } + $hashtable2 = @{ + Name = $TestRepoName2 + Priority = 25 + } + $incorrectHashTable = @{ + Name = $Name + Trusted = $True + } $arrayOfHashtables = $hashtable1, $incorrectHashTable, $hashtable2 Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue @@ -148,10 +157,25 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName3 -Uri $tmpDir3Path Register-PSResourceRepository -PSGallery - $hashtable1 = @{Name = $TestRepoName1; Uri = $tmpDir2Path}; - $hashtable2 = @{Name = $TestRepoName2; Priority = 25}; - $hashtable3 = @{Name = $TestRepoName3; CredentialInfo = [PSCustomObject] @{ VaultName = "testvault"; SecretName = $randomSecret }}; - $hashtable4 = @{Name = $PSGalleryName; Trusted = $True}; + $hashtable1 = @{ + Name = $TestRepoName1 + Uri = $tmpDir2Path + } + $hashtable2 = @{ + Name = $TestRepoName2 + Priority = 25 + } + $hashtable3 = @{ + Name = $TestRepoName3 + CredentialInfo = [PSCustomObject] @{ + VaultName = "testvault" + SecretName = $randomSecret + } + } + $hashtable4 = @{ + Name = $PSGalleryName + Trusted = $True + } $arrayOfHashtables = $hashtable1, $hashtable2, $hashtable3, $hashtable4 Set-PSResourceRepository -Repository $arrayOfHashtables @@ -189,13 +213,13 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { It "not set and throw error for trying to set PSGallery Uri (NameParameterSet)" { Unregister-PSResourceRepository -Name $PSGalleryName Register-PSResourceRepository -PSGallery - {Set-PSResourceRepository -Name $PSGalleryName -Uri $tmpDir1Path -ErrorAction Stop} | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" + { Set-PSResourceRepository -Name $PSGalleryName -Uri $tmpDir1Path -ErrorAction Stop } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" } It "not set and throw error for trying to set PSGallery CredentialInfo (NameParameterSet)" { Unregister-PSResourceRepository -Name $PSGalleryName Register-PSResourceRepository -PSGallery - {Set-PSResourceRepository -Name $PSGalleryName -CredentialInfo $credentialInfo1 -ErrorAction Stop} | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" + { Set-PSResourceRepository -Name $PSGalleryName -CredentialInfo $credentialInfo1 -ErrorAction Stop } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PSResourceGet.Cmdlets.SetPSResourceRepository" } It "not set repository and throw error for trying to set PSGallery Uri (RepositoriesParameterSet)" { @@ -204,8 +228,14 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path - $hashtable1 = @{Name = $PSGalleryName; Uri = $tmpDir1Path} - $hashtable2 = @{Name = $TestRepoName1; Priority = 25} + $hashtable1 = @{ + Name = $PSGalleryName + Uri = $tmpDir1Path + } + $hashtable2 = @{ + Name = $TestRepoName1 + Priority = 25 + } $arrayOfHashtables = $hashtable1, $hashtable2 Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue @@ -234,8 +264,14 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path - $hashtable1 = @{Name = $PSGalleryName; CredentialInfo = $credentialInfo1} - $hashtable2 = @{Name = $TestRepoName1; Priority = 25} + $hashtable1 = @{ + Name = $PSGalleryName + CredentialInfo = $credentialInfo1 + } + $hashtable2 = @{ + Name = $TestRepoName1 + Priority = 25 + } $arrayOfHashtables = $hashtable1, $hashtable2 Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue @@ -309,13 +345,13 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { } It "set repository with a hashtable passed in as CredentialInfo" { - $hashtable = @{VaultName = "testvault"; SecretName = $randomSecret} + $hashtable = @{VaultName = "testvault"; SecretName = $randomSecret } $newRandomSecret = [System.IO.Path]::GetRandomFileName() - $newHashtable = @{VaultName = "testvault"; SecretName = $newRandomSecret} + $newHashtable = @{VaultName = "testvault"; SecretName = $newRandomSecret } - Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $hashtable - Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $newHashtable + Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $hashtable + Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $newHashtable $res = Get-PSResourceRepository -Name $TestRepoName1 $res.CredentialInfo.VaultName | Should -Be "testvault" @@ -323,7 +359,7 @@ Describe "Test Set-PSResourceRepository" -tags 'CI' { $res.CredentialInfo.Credential | Should -BeNullOrEmpty } - It "should set temp drive repository" -skip:(!$IsWindows) { + It "should set temp drive repository" -skip:(!$IsWindows) { Register-PSResourceRepository -Name "tempDriveRepo" -Uri $tmpDir1Path $res = Get-PSResourceRepository -Name "tempDriveRepo" $res.Uri.LocalPath | Should -Be $tmpDir1Path diff --git a/test/ResourceRepositoryTests/UnregisterPSResourceRepository.Tests.ps1 b/test/ResourceRepositoryTests/UnregisterPSResourceRepository.Tests.ps1 index 1ed6818a1..981b2f944 100644 --- a/test/ResourceRepositoryTests/UnregisterPSResourceRepository.Tests.ps1 +++ b/test/ResourceRepositoryTests/UnregisterPSResourceRepository.Tests.ps1 @@ -36,15 +36,15 @@ Describe "Test Unregister-PSResourceRepository" -tags 'CI' { It "unregister multiple repositories previously registered" { Register-PSResourceRepository -Name "testRepository" -Uri $tmpDir1Path Register-PSResourceRepository -Name "testRepository2" -Uri $tmpDir2Path - Unregister-PSResourceRepository -Name "testRepository","testRepository2" + Unregister-PSResourceRepository -Name "testRepository", "testRepository2" - $res = Get-PSResourceRepository -Name "testRepository","testRepository2" -ErrorVariable err -ErrorAction SilentlyContinue + $res = Get-PSResourceRepository -Name "testRepository", "testRepository2" -ErrorVariable err -ErrorAction SilentlyContinue $res | Should -BeNullOrEmpty } It "not unregister repo not previously registered and throw expected error message" { $name = "nonRegisteredRepository" - {Unregister-PSResourceRepository -Name $name -ErrorAction Stop} | Should -Throw -ErrorId "ErrorUnregisteringSpecifiedRepo,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" + { Unregister-PSResourceRepository -Name $name -ErrorAction Stop } | Should -Throw -ErrorId "ErrorUnregisteringSpecifiedRepo,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" } @@ -59,17 +59,17 @@ Describe "Test Unregister-PSResourceRepository" -tags 'CI' { It "when multiple repo Names provided, if one name isn't valid unregister the rest and write error message" { $nonRegisteredRepoName = "nonRegisteredRepository" Register-PSResourceRepository -Name "testRepository" -Uri $tmpDir1Path - Unregister-PSResourceRepository -Name $nonRegisteredRepoName,"testRepository" -ErrorVariable err -ErrorAction SilentlyContinue + Unregister-PSResourceRepository -Name $nonRegisteredRepoName, "testRepository" -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -BeGreaterThan 0 $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorUnregisteringSpecifiedRepo,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" } It "throw error if Name is null or empty" { - {Unregister-PSResourceRepository -Name "" -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" + { Unregister-PSResourceRepository -Name "" -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" } It "throw error if Name is null" { - {Unregister-PSResourceRepository -Name $null -ErrorAction Stop} | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" + { Unregister-PSResourceRepository -Name $null -ErrorAction Stop } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.PSResourceGet.Cmdlets.UnregisterPSResourceRepository" } It "unregister repository using -PassThru" { diff --git a/test/SavePSResourceTests/SavePSResourceLocalTests.ps1 b/test/SavePSResourceTests/SavePSResourceLocalTests.ps1 index 36eb5330c..16e73a1ea 100644 --- a/test/SavePSResourceTests/SavePSResourceLocalTests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceLocalTests.ps1 @@ -9,7 +9,7 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { BeforeAll { $localRepo = "psgettestlocal" - $localUNCRepo = "psgettestlocal3" + $localUNCRepo = "psgettestlocal3" $moduleName = "test_local_mod" $moduleName2 = "test_local_mod2" $moduleName3 = "testModule99" @@ -24,7 +24,7 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { $SaveDir = Join-Path $TestDrive 'SavedResources' $saveItem = New-Item -Item Directory $SaveDir -Force - $SaveDirUNC = $saveItem.FullName -Replace '^(.):', '\\localhost\$1$' + $SaveDirUNC = $saveItem.FullName -Replace '^(.):', '\\localhost\$1$' } AfterEach { @@ -43,21 +43,21 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { (Get-ChildItem $pkgDir.FullName) | Should -HaveCount 1 } - It "Save specific module resource by name from UNC repository" { + It "Save specific module resource by name from UNC repository" { Save-PSResource -Name $moduleName -Repository $localUNCRepo -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName $pkgDir | Should -Not -BeNullOrEmpty (Get-ChildItem $pkgDir.FullName) | Should -HaveCount 1 } - It "Save specific module resource by name to a UNC path" { + It "Save specific module resource by name to a UNC path" { Save-PSResource -Name $moduleName -Repository $localRepo -Path $SaveDirUNC -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDirUNC | Where-Object Name -eq $moduleName $pkgDir | Should -Not -BeNullOrEmpty (Get-ChildItem $pkgDir.FullName) | Should -HaveCount 1 } - It "Save specific module resource by name from UNC repository to a UNC path" { + It "Save specific module resource by name from UNC repository to a UNC path" { Save-PSResource -Name $moduleName -Repository $localUNCRepo -Path $SaveDirUNC -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDirUNC | Where-Object Name -eq $moduleName $pkgDir | Should -Not -BeNullOrEmpty @@ -96,7 +96,7 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { $pkgDirVersion = Get-ChildItem $pkgDir.FullName $pkgDirVersion.Name | Should -Be "1.0.0" } - + It "Should save resource given name and version '3.*'" { Save-PSResource -Name $moduleName -Version "3.*" -Repository $localRepo -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName @@ -113,13 +113,13 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { $pkgDirVersion.Name | Should -Be "1.0.0" } - It "Should save resource given name and exact range inclusive [1.0.0, 3.0.0]" { - Save-PSResource -Name $moduleName -Version "[1.0.0, 3.0.0]" -Repository $localRepo -Path $SaveDir -TrustRepository - $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName - $pkgDir | Should -Not -BeNullOrEmpty - $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName - $pkgDirVersion.Name | Should -Be "3.0.0" - } + It "Should save resource given name and exact range inclusive [1.0.0, 3.0.0]" { + Save-PSResource -Name $moduleName -Version "[1.0.0, 3.0.0]" -Repository $localRepo -Path $SaveDir -TrustRepository + $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName + $pkgDir | Should -Not -BeNullOrEmpty + $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName + $pkgDirVersion.Name | Should -Be "3.0.0" + } It "Should save resource given name and exact range exclusive (1.0.0, 5.0.0)" { Save-PSResource -Name $moduleName -Version "(1.0.0, 5.0.0)" -Repository $localRepo -Path $SaveDir -TrustRepository @@ -130,11 +130,10 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { } It "Should not save resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { - $Version="(1.0.0.0)" + $Version = "(1.0.0.0)" try { Save-PSResource -Name $moduleName -Version $Version -Repository $localRepo -Path $SaveDir -ErrorAction SilentlyContinue -TrustRepository - } - catch + } catch {} $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName @@ -147,7 +146,7 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { Find-PSResource -Name $moduleName -Version "5.0.0" -Repository $localRepo | Save-PSResource -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $moduleName $pkgDir | Should -Not -BeNullOrEmpty - (Get-ChildItem -Path $pkgDir.FullName) | Should -HaveCount 1 + (Get-ChildItem -Path $pkgDir.FullName) | Should -HaveCount 1 } It "Save module as a nupkg" { @@ -157,7 +156,7 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { } It "Save module, should search through all repositories and only install from the first repo containing the package" { - Save-PSResource -Name $moduleName3 -Version "0.0.93" -Path $SaveDir -TrustRepository -ErrorVariable ev + Save-PSResource -Name $moduleName3 -Version "0.0.93" -Path $SaveDir -TrustRepository -ErrorVariable ev $ev | Should -BeNullOrEmpty $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq "$moduleName3" $pkgDir | Should -Not -BeNullOrEmpty @@ -180,11 +179,11 @@ Describe 'Test Save-PSResource for local repositories' -tags 'CI' { } It "Save module via InputObject by piping from Find-PSResource" { - $modules = Find-PSResource -Name "*" -Repository $localRepo + $modules = Find-PSResource -Name "*" -Repository $localRepo $modules.Count | Should -BeGreaterThan 1 Save-PSResource -Path $SaveDir -TrustRepository -InputObject $modules - + $pkgDir = Get-ChildItem -Path $SaveDir $pkgDir | Should -Not -BeNullOrEmpty $pkgDir.Count | Should -BeGreaterThan 1 diff --git a/test/SavePSResourceTests/SavePSResourceV2Tests.ps1 b/test/SavePSResourceTests/SavePSResourceV2Tests.ps1 index f00656b06..a73f26f02 100644 --- a/test/SavePSResourceTests/SavePSResourceV2Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceV2Tests.ps1 @@ -104,11 +104,10 @@ Describe 'Test HTTP Save-PSResource for V2 Server Protocol' -tags 'CI' { } It "Should not save resource with incorrectly formatted version such as exclusive version (1.0.0.0)" { - $Version="(1.0.0.0)" + $Version = "(1.0.0.0)" try { Save-PSResource -Name $testModuleName -Version $Version -Repository $PSGalleryName -Path $SaveDir -ErrorAction SilentlyContinue -TrustRepository - } - catch + } catch {} $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName @@ -127,7 +126,7 @@ Describe 'Test HTTP Save-PSResource for V2 Server Protocol' -tags 'CI' { It "Save a module with a dependency" { Save-PSResource -Name "TestModuleWithDependencyE" -Version "1.0.0.0" -Repository $PSGalleryName -Path $SaveDir -TrustRepository - $pkgDirs = Get-ChildItem -Path $SaveDir | Where-Object { $_.Name -eq "TestModuleWithDependencyE" -or $_.Name -eq "TestModuleWithDependencyC" -or $_.Name -eq "TestModuleWithDependencyB" -or $_.Name -eq "TestModuleWithDependencyD"} + $pkgDirs = Get-ChildItem -Path $SaveDir | Where-Object { $_.Name -eq "TestModuleWithDependencyE" -or $_.Name -eq "TestModuleWithDependencyC" -or $_.Name -eq "TestModuleWithDependencyB" -or $_.Name -eq "TestModuleWithDependencyD" } $pkgDirs.Count | Should -BeGreaterThan 1 (Get-ChildItem $pkgDirs[0].FullName).Count | Should -BeGreaterThan 0 (Get-ChildItem $pkgDirs[1].FullName).Count | Should -BeGreaterThan 0 @@ -137,7 +136,7 @@ Describe 'Test HTTP Save-PSResource for V2 Server Protocol' -tags 'CI' { It "Save a module with a dependency and skip saving the dependency" { Save-PSResource -Name "TestModuleWithDependencyE" -Version "1.0.0.0" -SkipDependencyCheck -Repository $PSGalleryName -Path $SaveDir -TrustRepository - $pkgDirs = Get-ChildItem -Path $SaveDir | Where-Object { $_.Name -eq "TestModuleWithDependencyE"} + $pkgDirs = Get-ChildItem -Path $SaveDir | Where-Object { $_.Name -eq "TestModuleWithDependencyE" } $pkgDirs | Should -HaveCount 1 (Get-ChildItem $pkgDirs[0].FullName) | Should -HaveCount 1 } diff --git a/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 b/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 index 11dbb9688..5474d3b9b 100644 --- a/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceV3Tests.ps1 @@ -87,11 +87,10 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { } It 'Should not save resource with incorrectly formatted version such as exclusive version (1.0.0.0)' { - $Version='(1.0.0.0)' + $Version = '(1.0.0.0)' try { Save-PSResource -Name $testModuleName -Version $Version -Repository $NuGetGalleryName -Path $SaveDir -ErrorAction SilentlyContinue -TrustRepository - } - catch { + } catch { } $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName @@ -110,7 +109,7 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { ### TODO: this is broken because the "Prerelease" parameter is a boolean, but the type from ### the input object is of type string (ie "true"). - It 'Save PSResourceInfo object piped in for prerelease version object' -Pending{ + It 'Save PSResourceInfo object piped in for prerelease version object' -Pending { Find-PSResource -Name $testModuleName -Version '5.2.5-alpha001' -Repository $NuGetGalleryName | Save-PSResource -Path $SaveDir -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -EQ $testModuleName $pkgDir | Should -Not -BeNullOrEmpty @@ -155,7 +154,7 @@ Describe 'Test HTTP Save-PSResource for V3 Server Protocol' -tags 'CI' { $pkg.Name | Should -Be 'test_module_withlicense' $pkg.Version | Should -Be '1.0.0' } - + It "Save module and its dependencies" { $res = Save-PSResource 'TestModuleWithDependencyE' -Repository $NuGetGalleryName -TrustRepository -PassThru $res.Length | Should -Be 4 diff --git a/test/TestRequiredResourceFile.psd1 b/test/TestRequiredResourceFile.psd1 index 71eba50fa..b74231e83 100644 --- a/test/TestRequiredResourceFile.psd1 +++ b/test/TestRequiredResourceFile.psd1 @@ -1,16 +1,16 @@ - @{ - test_module = @{ - version = "[1.0.0,5.0.0)" +@{ + test_module = @{ + version = "[1.0.0,5.0.0)" repository = "PSGallery" - } - + } + test_module2 = @{ - version = "[1.0.0,3.0.0)" - repository = "PSGallery" - prerelease = "true" + version = "[1.0.0,3.0.0)" + repository = "PSGallery" + prerelease = "true" } - + TestModule99 = @{ - repository = "PSGallery" + repository = "PSGallery" } } diff --git a/test/UninstallPSResourceTests/UninstallPSResource.Tests.ps1 b/test/UninstallPSResourceTests/UninstallPSResource.Tests.ps1 index eed558be7..0a7845b14 100644 --- a/test/UninstallPSResourceTests/UninstallPSResource.Tests.ps1 +++ b/test/UninstallPSResourceTests/UninstallPSResource.Tests.ps1 @@ -7,7 +7,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { - BeforeAll{ + BeforeAll { $PSGalleryName = Get-PSGalleryName $testModuleName = "test_module2" $testScriptName = "test_script" @@ -35,8 +35,8 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { Get-InstalledPSResource $testModuleName | Should -BeNullOrEmpty } - $testCases = @{Name="Test?Module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"}, - @{Name="Test[Module"; ErrorId="ErrorFilteringNamesForUnsupportedWildcards"} + $testCases = @{Name = "Test?Module"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" }, + @{Name = "Test[Module"; ErrorId = "ErrorFilteringNamesForUnsupportedWildcards" } It "not uninstall module given Name with invalid wildcard characters" -TestCases $testCases { param($Name, $ErrorId) @@ -110,15 +110,15 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { $pkgs.Version | Should -Not -Contain "1.0.0" } - $testCases = @{Version="[1.0.0.0]"; ExpectedVersion="1.0.0.0"; Reason="validate version, exact match"}, - @{Version="1.0.0.0"; ExpectedVersion="1.0.0.0"; Reason="validate version, exact match without bracket syntax"}, - @{Version="[1.0.0.0, 5.0.0.0]"; ExpectedVersion="5.0.0.0"; Reason="validate version, exact range inclusive"}, - @{Version="(1.0.0.0, 5.0.0.0)"; ExpectedVersion="3.0.0.0"; Reason="validate version, exact range exclusive"}, - @{Version="(1.0.0.0,)"; ExpectedVersion="5.0.0.0"; Reason="validate version, minimum version exclusive"}, - @{Version="[1.0.0.0,)"; ExpectedVersion="5.0.0.0"; Reason="validate version, minimum version inclusive"}, - @{Version="(,3.0.0.0)"; ExpectedVersion="1.0.0.0"; Reason="validate version, maximum version exclusive"}, - @{Version="(,3.0.0.0]"; ExpectedVersion="1.0.0.0"; Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; ExpectedVersion="3.0.0.0"; Reason="validate version, mixed inclusive minimum and exclusive maximum version"} + $testCases = @{Version = "[1.0.0.0]"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, exact match" }, + @{Version = "1.0.0.0"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[1.0.0.0, 5.0.0.0]"; ExpectedVersion = "5.0.0.0"; Reason = "validate version, exact range inclusive" }, + @{Version = "(1.0.0.0, 5.0.0.0)"; ExpectedVersion = "3.0.0.0"; Reason = "validate version, exact range exclusive" }, + @{Version = "(1.0.0.0,)"; ExpectedVersion = "5.0.0.0"; Reason = "validate version, minimum version exclusive" }, + @{Version = "[1.0.0.0,)"; ExpectedVersion = "5.0.0.0"; Reason = "validate version, minimum version inclusive" }, + @{Version = "(,3.0.0.0)"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, maximum version exclusive" }, + @{Version = "(,3.0.0.0]"; ExpectedVersion = "1.0.0.0"; Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; ExpectedVersion = "3.0.0.0"; Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } It "Uninstall module when given Name to " -TestCases $testCases { param($Version, $ExpectedVersion) @@ -132,23 +132,23 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { $pkgs.Version | Should -Not -Contain $Version } - $testCases2 = @{Version='[1.*.0]'; Description="version with wilcard in middle"}, - @{Version='[*.0.0.0]'; Description="version with wilcard at start"}, - @{Version='[1.*.0.0]'; Description="version with wildcard at second digit"}, - @{Version='[1.0.*.0]'; Description="version with wildcard at third digit"} - @{Version='[1.0.0.*]'; Description="version with wildcard at end"}, - @{Version='[1..0.0]'; Description="version with missing digit in middle"}, - @{Version='[1.0.0.]'; Description="version with missing digit at end"}, - @{Version='[1.0.0.0.0]'; Description="version with more than 4 digits"} + $testCases2 = @{Version = '[1.*.0]'; Description = "version with wilcard in middle" }, + @{Version = '[*.0.0.0]'; Description = "version with wilcard at start" }, + @{Version = '[1.*.0.0]'; Description = "version with wildcard at second digit" }, + @{Version = '[1.0.*.0]'; Description = "version with wildcard at third digit" } + @{Version = '[1.0.0.*]'; Description = "version with wildcard at end" }, + @{Version = '[1..0.0]'; Description = "version with missing digit in middle" }, + @{Version = '[1.0.0.]'; Description = "version with missing digit at end" }, + @{Version = '[1.0.0.0.0]'; Description = "version with more than 4 digits" } It "Do not uninstall module with incorrectly formatted version such as " -TestCases $testCases2 { param($Version, $Description) - {Uninstall-PSResource -Name $testModuleName -Version $Version -SkipDependencyCheck} | Should -Throw "Argument for -Version parameter is not in the proper format." + { Uninstall-PSResource -Name $testModuleName -Version $Version -SkipDependencyCheck } | Should -Throw "Argument for -Version parameter is not in the proper format." } - $testCases3 = @{Version='(1.0.0.0)'; Description="exclusive version (1.0.0.0)"}, - @{Version='[1-0-0-0]'; Description="version formatted with invalid delimiter"} + $testCases3 = @{Version = '(1.0.0.0)'; Description = "exclusive version (1.0.0.0)" }, + @{Version = '[1-0-0-0]'; Description = "version formatted with invalid delimiter" } It "Do not uninstall module with incorrectly formatted version such as " -TestCases $testCases3 { param($Version, $Description) @@ -157,8 +157,7 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { try { Uninstall-PSResource -Name $testModuleName -Version $Version -ErrorAction SilentlyContinue -SkipDependencyCheck - } - catch + } catch {} $pkg = Get-InstalledPSResource $testModuleName -Version "1.0.0.0" $pkg.Version | Should -Be "1.0.0.0" @@ -203,14 +202,14 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { Install-PSResource -Name $testModuleName -Version "5.0.0" -Repository $PSGalleryName -TrustRepository Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $PSGalleryName -TrustRepository $res = Get-InstalledPSResource -Name $testModuleName - $prereleaseVersionPkgs = $res | Where-Object {$_.IsPrerelease -eq $true} + $prereleaseVersionPkgs = $res | Where-Object { $_.IsPrerelease -eq $true } $prereleaseVersionPkgs.Count | Should -Be 2 Uninstall-PSResource -Name $testModuleName -Version "*" -Prerelease -SkipDependencyCheck $res = Get-InstalledPSResource -Name $testModuleName - $prereleaseVersionPkgs = $res | Where-Object {$_.IsPrerelease -eq $true} + $prereleaseVersionPkgs = $res | Where-Object { $_.IsPrerelease -eq $true } $prereleaseVersionPkgs.Count | Should -Be 0 - $stableVersionPkgs = $res | Where-Object {$_.IsPrerelease -ne $true} + $stableVersionPkgs = $res | Where-Object { $_.IsPrerelease -ne $true } $stableVersionPkgs.Count | Should -Be 2 } @@ -222,15 +221,15 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { Install-PSResource -Name $testModuleName -Version "5.2.5-alpha001" -Repository $PSGalleryName -TrustRepository $res = Get-InstalledPSResource -Name $testModuleName - $prereleaseVersionPkgs = $res | Where-Object {$_.IsPrerelease -eq $true} + $prereleaseVersionPkgs = $res | Where-Object { $_.IsPrerelease -eq $true } $prereleaseVersionPkgs.Count | Should -Be 2 Uninstall-PSResource -Name $testModuleName -Version "[2.0.0, 5.0.0]" -Prerelease -SkipDependencyCheck $res = Get-InstalledPSResource -Name $testModuleName # should only uninstall 2.5.0-beta, 5.2.5-alpha001 is out of range and should remain installed - $prereleaseVersionPkgs = $res | Where-Object {$_.IsPrerelease -eq $true} + $prereleaseVersionPkgs = $res | Where-Object { $_.IsPrerelease -eq $true } $prereleaseVersionPkgs.Count | Should -Be 1 - $stableVersionPkgs = $res | Where-Object {$_.IsPrerelease -ne $true} + $stableVersionPkgs = $res | Where-Object { $_.IsPrerelease -ne $true } # versions 3.0.0 falls in range but should not be uninstalled as Prerelease parameter only selects prerelease versions to uninstall $stableVersionPkgs.Count | Should -Be 2 } @@ -243,8 +242,8 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { $pkg = Get-InstalledPSResource $testModuleName -Version "5.0.0.0" $pkg.Version | Should -Be "5.0.0.0" - $match = Get-Content .\testUninstallWhatIf.txt | - select-string -pattern "What if: Performing the operation ""Uninstall-PSResource"" on target ""Uninstall resource 'test_module2', version '5.0.0.0', from path '" -SimpleMatch + $match = Get-Content .\testUninstallWhatIf.txt | + select-string -pattern "What if: Performing the operation ""Uninstall-PSResource"" on target ""Uninstall resource 'test_module2', version '5.0.0.0', from path '" -SimpleMatch $match -ne $null diff --git a/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 b/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 index d20d25076..c50528b0b 100644 --- a/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 +++ b/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 @@ -34,49 +34,48 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { It "Update module manifest given Guid parameter" { $Guid = [guid]::NewGuid() New-ModuleManifest -Path $script:testManifestPath - Update-PSModuleManifest -Path $script:testManifestPath -Guid $Guid + Update-PSModuleManifest -Path $script:testManifestPath -Guid $Guid $results = Test-ModuleManifest -Path $script:testManifestPath - $results.Guid | Should -Be $Guid + $results.Guid | Should -Be $Guid } It "Update module manifest given Author parameter" { - $Author = "Test Author" + $Author = "Test Author" New-ModuleManifest -Path $script:testManifestPath - Update-PSModuleManifest -Path $script:testManifestPath -Author $Author + Update-PSModuleManifest -Path $script:testManifestPath -Author $Author $results = Test-ModuleManifest -Path $script:testManifestPath - $results.Author | Should -Be $Author + $results.Author | Should -Be $Author } It "Update module manifest given Description parameter" { $Description = "PSResourceGet test description" New-ModuleManifest -Path $script:testManifestPath - Update-PSModuleManifest -Path $script:testManifestPath -Description $Description + Update-PSModuleManifest -Path $script:testManifestPath -Description $Description $results = Test-ModuleManifest -Path $script:testManifestPath - $results.Description | Should -Be $Description + $results.Description | Should -Be $Description } It "Update module manifest given ModuleVersion parameter" { - $ModuleVersion = "7.0.0.0" + $ModuleVersion = "7.0.0.0" New-ModuleManifest -Path $script:testManifestPath - Update-PSModuleManifest -Path $script:testManifestPath -ModuleVersion $ModuleVersion + Update-PSModuleManifest -Path $script:testManifestPath -ModuleVersion $ModuleVersion $results = Test-ModuleManifest -Path $script:testManifestPath - $results.Version.ToString() | Should -Be $ModuleVersion + $results.Version.ToString() | Should -Be $ModuleVersion } It "Update module manifest given RequiredModules parameter" { $requiredModuleName = 'PackageManagement' $requiredModuleVersion = '1.0.0.0' - $RequiredModules = @(@{ModuleName = $requiredModuleName; ModuleVersion = $requiredModuleVersion }) + $RequiredModules = @(@{ModuleName = $requiredModuleName; ModuleVersion = $requiredModuleVersion }) New-ModuleManifest -Path $script:testManifestPath Update-PSModuleManifest -Path $script:testManifestPath -RequiredModules $RequiredModules -Description "test" $results = Test-ModuleManifest -Path $script:testManifestPath - foreach ($module in $results.RequiredModules) - { + foreach ($module in $results.RequiredModules) { $module | Should -Be $requiredModuleName $module.Version | Should -Be $requiredModuleVersion } @@ -98,7 +97,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { $ModuleVersion = "1.0.0" $Prerelease = " " New-ModuleManifest -Path $script:testManifestPath -Description $Description -ModuleVersion $ModuleVersion - {Update-PSModuleManifest -Path $script:testManifestPath -Prerelease $Prerelease} | Should -Throw -ErrorId "PrereleaseValueCannotBeWhiteSpace,Microsoft.PowerShell.PSResourceGet.Cmdlets.UpdateModuleManifest" + { Update-PSModuleManifest -Path $script:testManifestPath -Prerelease $Prerelease } | Should -Throw -ErrorId "PrereleaseValueCannotBeWhiteSpace,Microsoft.PowerShell.PSResourceGet.Cmdlets.UpdateModuleManifest" } It "Update module manifest given ReleaseNotes parameter" { @@ -121,7 +120,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -Tags $Tag1, $Tag2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.PrivateData.PSData.Tags | Should -Be @($Tag1, $Tag2) + $results.PrivateData.PSData.Tags | Should -Be @($Tag1, $Tag2) } It "Update module manifest given Tag parameter" { @@ -132,7 +131,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-ModuleManifest -Path $script:testManifestPath -Tag $Tag1, $Tag2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.PrivateData.PSData.Tags | Should -Be @($Tag1, $Tag2) + $results.PrivateData.PSData.Tags | Should -Be @($Tag1, $Tag2) } It "Update module manifest given ProjectUri parameter" { @@ -225,7 +224,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -RootModule $RootModuleName $results = Test-ModuleManifest -Path $script:testManifestPath - $results.RootModule | Should -Be $RootModuleName + $results.RootModule | Should -Be $RootModuleName } It "Update module manifest given RequiredAssemblies parameter" { @@ -242,7 +241,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -RequiredAssemblies $RequiredAssembly1, $RequiredAssembly2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.RequiredAssemblies | Should -Be @($RequiredAssembly1, $RequiredAssembly2) + $results.RequiredAssemblies | Should -Be @($RequiredAssembly1, $RequiredAssembly2) } It "Update module manifest given NestedModules parameter" { @@ -261,7 +260,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -NestedModules $NestedModule1, $NestedModule2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.NestedModules | Should -Be @($NestedModule1, $NestedModule2) + $results.NestedModules | Should -Be @($NestedModule1, $NestedModule2) } It "Update module manifest given FileList parameter" { @@ -278,7 +277,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -FileList $FileList1, $FileList2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.FileList | Should -Be @($FileListPath1, $FileListPath2) + $results.FileList | Should -Be @($FileListPath1, $FileListPath2) } It "Update module manifest given TypesToProcess parameter" { @@ -323,7 +322,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -ScriptsToProcess $Script1, $Script2 $results = Test-ModuleManifest -Path $script:testManifestPath - $results.Scripts | Should -Be @($ScriptPath1, $ScriptPath2) + $results.Scripts | Should -Be @($ScriptPath1, $ScriptPath2) } It "Update module manifest given ProcessorArchitecture parameter" { @@ -333,7 +332,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { Update-PSModuleManifest -Path $script:testManifestPath -ProcessorArchitecture $ProcessorArchitecture $results = Test-ModuleManifest -Path $script:testManifestPath - $results.ProcessorArchitecture | Should -Be $ProcessorArchitecture + $results.ProcessorArchitecture | Should -Be $ProcessorArchitecture } It "Update module manifest given ModuleList parameter" { @@ -359,24 +358,24 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { New-ModuleManifest -Path $script:testManifestPath -Description $Description Update-PSModuleManifest -Path $script:testManifestPath ` - -CompanyName $CompanyName ` - -Copyright $Copyright ` - -PowerShellVersion $PowerShellVersion ` - -ClrVersion $ClrVersion ` - -DotNetFrameworkVersion $DotnetFrameworkVersion ` - -PowerShellHostVersion $PowerShellHostVersion ` - -HelpInfoUri $HelpInfoUri ` - -CompatiblePSEditions $CompatiblePSEditions + -CompanyName $CompanyName ` + -Copyright $Copyright ` + -PowerShellVersion $PowerShellVersion ` + -ClrVersion $ClrVersion ` + -DotNetFrameworkVersion $DotnetFrameworkVersion ` + -PowerShellHostVersion $PowerShellHostVersion ` + -HelpInfoUri $HelpInfoUri ` + -CompatiblePSEditions $CompatiblePSEditions $results = Test-ModuleManifest -Path $script:testManifestPath - $results.CompanyName | Should -Be $CompanyName - $results.Copyright | Should -Be $Copyright - $results.PowerShellVersion | Should -Be $PowerShellVersion - $results.ClrVersion | Should -Be $ClrVersion - $results.DotnetFrameworkVersion | Should -Be $DotnetFrameworkVersion - $results.PowerShellHostVersion | Should -Be $PowerShellHostVersion - $results.HelpInfoUri | Should -Be $HelpInfoUri - $results.CompatiblePSEditions | Should -Be $CompatiblePSEditions + $results.CompanyName | Should -Be $CompanyName + $results.Copyright | Should -Be $Copyright + $results.PowerShellVersion | Should -Be $PowerShellVersion + $results.ClrVersion | Should -Be $ClrVersion + $results.DotnetFrameworkVersion | Should -Be $DotnetFrameworkVersion + $results.PowerShellHostVersion | Should -Be $PowerShellHostVersion + $results.HelpInfoUri | Should -Be $HelpInfoUri + $results.CompatiblePSEditions | Should -Be $CompatiblePSEditions } It "Update module manifest given FunctionsToExport, AliasesToExport, and VariablesToExport parameters" -Skip:(Get-IsWindows) { @@ -386,9 +385,9 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { $ExportedVariables = "VariablesToExport1", "Variables2Export2" New-ModuleManifest -Path $script:testManifestPath -Description $Description Update-PSModuleManifest -Path $script:testManifestPath ` - -FunctionsToExport $ExportedFunctions ` - -AliasesToExport $ExportedAliases ` - -VariablesToExport $ExportedVariables + -FunctionsToExport $ExportedFunctions ` + -AliasesToExport $ExportedAliases ` + -VariablesToExport $ExportedVariables $results = Test-ModuleManifest -Path $script:testManifestPath $results.ExportedFunctions.Keys | Should -Be $ExportedFunctions diff --git a/test/UpdatePSResourceTests/UpdatePSResourceLocalTests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceLocalTests.ps1 index f5334be83..37e05c640 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceLocalTests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceLocalTests.ps1 @@ -41,10 +41,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0") { $isPkgUpdated = $true } } @@ -60,14 +58,11 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $isPkgUpdated = $false $isCorrectRepo = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0") { $isPkgUpdated = $true - if ($pkg.Repository -eq $localRepo2) - { + if ($pkg.Repository -eq $localRepo2) { $isCorrectRepo = $true } } @@ -84,19 +79,14 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { Update-PSResource -Name "test_local*" -Repository $localRepo -TrustRepository $res = Get-InstalledPSResource -Name "test_local*" -Version "5.0.0" - $inputHashtable = @{test_module = "1.0.0"; test_module2 = "1.0.0"} + $inputHashtable = @{test_module = "1.0.0"; test_module2 = "1.0.0" } $isTest_ModuleUpdated = $false $isTest_Module2Updated = $false - foreach ($item in $res) - { - if ([System.Version]$item.Version -gt [System.Version]$inputHashtable[$item.Name]) - { - if ($item.Name -like $moduleName) - { + foreach ($item in $res) { + if ([System.Version]$item.Version -gt [System.Version]$inputHashtable[$item.Name]) { + if ($item.Name -like $moduleName) { $isTest_ModuleUpdated = $true - } - elseif ($item.Name -like $moduleName2) - { + } elseif ($item.Name -like $moduleName2) { $isTest_Module2Updated = $true } } @@ -112,10 +102,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { Update-PSResource -Name $moduleName -Version "5.0.0" -Repository $localRepo -TrustRepository $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0") { $isPkgUpdated = $true } } @@ -129,10 +117,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { Update-PSResource -Name $moduleName -Version "3.*" -Repository $localRepo -TrustRepository $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"3.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"3.0.0") { $isPkgUpdated = $true } } @@ -151,10 +137,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -174,10 +158,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res.Version | Should -Contain "5.0.0" $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.ModuleBase.Contains("Program") | Should -Be $true $isPkgUpdated = $true } @@ -194,10 +176,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -218,10 +198,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -241,10 +219,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("usr") | Should -Be $true $isPkgUpdated = $true } @@ -265,10 +241,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -301,10 +275,8 @@ Describe 'Test Update-PSResource for local repositories' -tags 'CI' { $res = Get-InstalledPSResource -Name $moduleName $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } diff --git a/test/UpdatePSResourceTests/UpdatePSResourceV2Tests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceV2Tests.ps1 index 0141e3e30..156bad70f 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceV2Tests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceV2Tests.ps1 @@ -19,7 +19,7 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { } AfterEach { - Uninstall-PSResource "test_module", "TestModule99", "TestModuleWithLicense", "test_module2", "test_script" -Version "*" -ErrorAction SilentlyContinue + Uninstall-PSResource "test_module", "TestModule99", "TestModuleWithLicense", "test_module2", "test_script" -Version "*" -ErrorAction SilentlyContinue } AfterAll { @@ -33,10 +33,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } @@ -51,19 +49,14 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { Update-PSResource -Name "test_mod*" -Repository $PSGalleryName -TrustRepository $res = Get-InstalledPSResource -Name "test_mod*" -Version "5.0.0.0" $res | Should -Not -BeNullOrEmpty - $inputHashtable = @{test_module = "1.0.0.0"; test_module2 = "1.0.0.0"} + $inputHashtable = @{test_module = "1.0.0.0"; test_module2 = "1.0.0.0" } $isTest_ModuleUpdated = $false $isTest_Module2Updated = $false - foreach ($item in $res) - { - if ([System.Version]$item.Version -gt [System.Version]$inputHashtable[$item.Name]) - { - if ($item.Name -like $testModuleName) - { + foreach ($item in $res) { + if ([System.Version]$item.Version -gt [System.Version]$inputHashtable[$item.Name]) { + if ($item.Name -like $testModuleName) { $isTest_ModuleUpdated = $true - } - elseif ($item.Name -like $testModuleName2) - { + } elseif ($item.Name -like $testModuleName2) { $isTest_Module2Updated = $true } } @@ -80,10 +73,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0.0") { $isPkgUpdated = $true } } @@ -91,18 +82,18 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $isPkgUpdated | Should -BeTrue } - $testCases2 = @{Version="[3.0.0.0]"; UpdatedVersion="3.0.0.0"; Reason="validate version, exact match"}, - @{Version="3.0.0.0"; UpdatedVersion="3.0.0.0"; Reason="validate version, exact match without bracket syntax"}, - @{Version="[3.0.0.0, 5.0.0.0]"; UpdatedVersion="5.0.0.0"; Reason="validate version, exact range inclusive"}, - @{Version="(3.0.0.0, 6.0.0.0)"; UpdatedVersion="5.0.0.0"; Reason="validate version, exact range exclusive"}, - @{Version="(3.0.0.0,)"; UpdatedVersion="5.0.0.0"; Reason="validate version, minimum version exclusive"}, - @{Version="[3.0.0.0,)"; UpdatedVersion="5.0.0.0"; Reason="validate version, minimum version inclusive"}, - @{Version="(,5.0.0.0)"; UpdatedVersion="3.0.0.0"; Reason="validate version, maximum version exclusive"}, - @{Version="(,5.0.0.0]"; UpdatedVersion="5.0.0.0"; Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; UpdatedVersion="3.0.0.0"; Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 3.0.0.0]"; UpdatedVersion="3.0.0.0"; Reason="validate version, mixed exclusive minimum and inclusive maximum version"} - - It "Update resource when given Name to " -TestCases $testCases2{ + $testCases2 = @{Version = "[3.0.0.0]"; UpdatedVersion = "3.0.0.0"; Reason = "validate version, exact match" }, + @{Version = "3.0.0.0"; UpdatedVersion = "3.0.0.0"; Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[3.0.0.0, 5.0.0.0]"; UpdatedVersion = "5.0.0.0"; Reason = "validate version, exact range inclusive" }, + @{Version = "(3.0.0.0, 6.0.0.0)"; UpdatedVersion = "5.0.0.0"; Reason = "validate version, exact range exclusive" }, + @{Version = "(3.0.0.0,)"; UpdatedVersion = "5.0.0.0"; Reason = "validate version, minimum version exclusive" }, + @{Version = "[3.0.0.0,)"; UpdatedVersion = "5.0.0.0"; Reason = "validate version, minimum version inclusive" }, + @{Version = "(,5.0.0.0)"; UpdatedVersion = "3.0.0.0"; Reason = "validate version, maximum version exclusive" }, + @{Version = "(,5.0.0.0]"; UpdatedVersion = "5.0.0.0"; Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; UpdatedVersion = "3.0.0.0"; Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 3.0.0.0]"; UpdatedVersion = "3.0.0.0"; Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } + + It "Update resource when given Name to " -TestCases $testCases2 { param($Version, $UpdatedVersion) Install-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $PSGalleryName -TrustRepository @@ -113,10 +104,10 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { } $testCases = @( - @{Version='(3.0.0.0)'; Description="exclusive version (3.0.0.0)"}, - @{Version='[3-0-0-0]'; Description="version formatted with invalid delimiter [3-0-0-0]"} + @{Version = '(3.0.0.0)'; Description = "exclusive version (3.0.0.0)" }, + @{Version = '[3-0-0-0]'; Description = "version formatted with invalid delimiter [3-0-0-0]" } ) - It "Should not update resource with incorrectly formatted version such as " -TestCases $testCases{ + It "Should not update resource with incorrectly formatted version such as " -TestCases $testCases { param($Version, $Description) Install-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $PSGalleryName -TrustRepository @@ -125,10 +116,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } @@ -143,10 +132,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"3.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"3.0.0") { $isPkgUpdated = $true } } @@ -160,10 +147,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -ge [System.Version]"5.2.5") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -ge [System.Version]"5.2.5") { $pkg.Prerelease | Should -Be "alpha001" $isPkgUpdated = $true } @@ -178,10 +163,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"5.2.5") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"5.2.5") { $pkg.Prerelease | Should -Be "alpha001" $isPkgUpdated = $true } @@ -196,10 +179,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName3 $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -ge [System.Version]"1.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -ge [System.Version]"1.0.0") { $pkg.Prerelease | Should -Be "beta2" $isPkgUpdated = $true } @@ -219,10 +200,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -251,10 +230,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -275,10 +252,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -299,10 +274,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("usr") | Should -Be $true $isPkgUpdated = $true } @@ -323,10 +296,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -359,10 +330,8 @@ Describe 'Test HTTP Update-PSResource for V2 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } diff --git a/test/UpdatePSResourceTests/UpdatePSResourceV3Tests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceV3Tests.ps1 index 88ed957dc..26a026d13 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceV3Tests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceV3Tests.ps1 @@ -6,7 +6,7 @@ Import-Module $modPath -Force -Verbose Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { - BeforeAll{ + BeforeAll { $NuGetGalleryName = Get-NuGetGalleryName $testModuleName = "test_module" Get-NewPSResourceRepositoryFile @@ -26,10 +26,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } @@ -44,10 +42,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -eq [System.Version]"5.0.0") { $isPkgUpdated = $true } } @@ -55,18 +51,18 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $isPkgUpdated | Should -BeTrue } - $testCases2 = @{Version="[3.0.0.0]"; UpdatedVersion="3.0.0"; Reason="validate version, exact match"}, - @{Version="3.0.0.0"; UpdatedVersion="3.0.0"; Reason="validate version, exact match without bracket syntax"}, - @{Version="[3.0.0.0, 5.0.0.0]"; UpdatedVersion="5.0.0"; Reason="validate version, exact range inclusive"}, - @{Version="(3.0.0.0, 6.0.0.0)"; UpdatedVersion="5.0.0"; Reason="validate version, exact range exclusive"}, - @{Version="(3.0.0.0,)"; UpdatedVersion="5.0.0"; Reason="validate version, minimum version exclusive"}, - @{Version="[3.0.0.0,)"; UpdatedVersion="5.0.0"; Reason="validate version, minimum version inclusive"}, - @{Version="(,5.0.0.0)"; UpdatedVersion="3.0.0"; Reason="validate version, maximum version exclusive"}, - @{Version="(,5.0.0.0]"; UpdatedVersion="5.0.0"; Reason="validate version, maximum version inclusive"}, - @{Version="[1.0.0.0, 5.0.0.0)"; UpdatedVersion="3.0.0"; Reason="validate version, mixed inclusive minimum and exclusive maximum version"} - @{Version="(1.0.0.0, 3.0.0.0]"; UpdatedVersion="3.0.0"; Reason="validate version, mixed exclusive minimum and inclusive maximum version"} - - It "Update resource when given Name to " -TestCases $testCases2{ + $testCases2 = @{Version = "[3.0.0.0]"; UpdatedVersion = "3.0.0"; Reason = "validate version, exact match" }, + @{Version = "3.0.0.0"; UpdatedVersion = "3.0.0"; Reason = "validate version, exact match without bracket syntax" }, + @{Version = "[3.0.0.0, 5.0.0.0]"; UpdatedVersion = "5.0.0"; Reason = "validate version, exact range inclusive" }, + @{Version = "(3.0.0.0, 6.0.0.0)"; UpdatedVersion = "5.0.0"; Reason = "validate version, exact range exclusive" }, + @{Version = "(3.0.0.0,)"; UpdatedVersion = "5.0.0"; Reason = "validate version, minimum version exclusive" }, + @{Version = "[3.0.0.0,)"; UpdatedVersion = "5.0.0"; Reason = "validate version, minimum version inclusive" }, + @{Version = "(,5.0.0.0)"; UpdatedVersion = "3.0.0"; Reason = "validate version, maximum version exclusive" }, + @{Version = "(,5.0.0.0]"; UpdatedVersion = "5.0.0"; Reason = "validate version, maximum version inclusive" }, + @{Version = "[1.0.0.0, 5.0.0.0)"; UpdatedVersion = "3.0.0"; Reason = "validate version, mixed inclusive minimum and exclusive maximum version" } + @{Version = "(1.0.0.0, 3.0.0.0]"; UpdatedVersion = "3.0.0"; Reason = "validate version, mixed exclusive minimum and inclusive maximum version" } + + It "Update resource when given Name to " -TestCases $testCases2 { param($Version, $UpdatedVersion) Install-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $NuGetGalleryName -TrustRepository @@ -77,10 +73,10 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { } $testCases = @( - @{Version='(3.0.0.0)'; Description="exclusive version (3.0.0.0)"}, - @{Version='[3-0-0-0]'; Description="version formatted with invalid delimiter [3-0-0-0]"} + @{Version = '(3.0.0.0)'; Description = "exclusive version (3.0.0.0)" }, + @{Version = '[3-0-0-0]'; Description = "version formatted with invalid delimiter [3-0-0-0]" } ) - It "Should not update resource with incorrectly formatted version such as " -TestCases $testCases{ + It "Should not update resource with incorrectly formatted version such as " -TestCases $testCases { param($Version, $Description) Install-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $NuGetGalleryName -TrustRepository @@ -89,10 +85,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } @@ -106,10 +100,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -ge [System.Version]"5.2.5") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -ge [System.Version]"5.2.5") { $pkg.Prerelease | Should -Be "alpha001" $isPkgUpdated = $true } @@ -129,10 +121,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -161,10 +151,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("Documents") | Should -Be $true $isPkgUpdated = $true } @@ -185,10 +173,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -209,10 +195,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("usr") | Should -Be $true $isPkgUpdated = $true } @@ -233,10 +217,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $pkg.InstalledLocation.Contains("$env:HOME/.local") | Should -Be $true $isPkgUpdated = $true } @@ -269,10 +251,8 @@ Describe 'Test HTTP Update-PSResource for V3 Server Protocol' -tags 'CI' { $res = Get-InstalledPSResource -Name $testModuleName $res | Should -Not -BeNullOrEmpty $isPkgUpdated = $false - foreach ($pkg in $res) - { - if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") - { + foreach ($pkg in $res) { + if ([System.Version]$pkg.Version -gt [System.Version]"1.0.0.0") { $isPkgUpdated = $true } } diff --git a/test/perf/benchmarks/BenchmarksV2LocalRepo.cs b/test/perf/benchmarks/BenchmarksV2LocalRepo.cs index d6558228b..206eb3b8a 100644 --- a/test/perf/benchmarks/BenchmarksV2LocalRepo.cs +++ b/test/perf/benchmarks/BenchmarksV2LocalRepo.cs @@ -26,14 +26,14 @@ public void GlobalSetup() pwsh.AddScript("Import-Module PSResourceGet -Force"); pwsh.AddScript("New-Item TestRepo -ItemType Directory"); pwsh.AddScript("Save-PSResource -Name Az -Repository PSGallery -AsNupkg -TrustRepository -Path .\\TestRepo"); - + // Now import the PSGet module version we want to test and register a local repo pwsh.AddScript("Import-Module PowerShellGet -RequiredVersion 2.2.5 -Force"); pwsh.AddScript("Register-PSRepository -Name LocalRepo -SourceLocation .\\TestRepo"); pwsh.Invoke(); } - + [GlobalCleanup] public void GlobalCleanup() { diff --git a/test/perf/benchmarks/BenchmarksV2RemoteRepo.cs b/test/perf/benchmarks/BenchmarksV2RemoteRepo.cs index 913827e4d..264d1c735 100644 --- a/test/perf/benchmarks/BenchmarksV2RemoteRepo.cs +++ b/test/perf/benchmarks/BenchmarksV2RemoteRepo.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using BenchmarkDotNet; using BenchmarkDotNet.Attributes; using Microsoft.PowerShell; using System; @@ -26,13 +25,13 @@ public void GlobalSetup() pwsh.AddScript("Import-Module PowerShellGet -RequiredVersion 2.2.5 -Force"); pwsh.Invoke(); } - + [GlobalCleanup] public void IterationCleanup() { pwsh.Dispose(); } - + [Benchmark] public void FindAzModuleV2() { @@ -48,7 +47,7 @@ public void FindAzModuleAndDependenciesV2() pwsh.AddScript("Find-Module -Name Az -IncludeDependencies -Repository PSGallery"); pwsh.Invoke(); } - + [Benchmark] public void InstallAzModuleAndDependenciesV2() { diff --git a/test/perf/benchmarks/BenchmarksV3LocalRepo.cs b/test/perf/benchmarks/BenchmarksV3LocalRepo.cs index fde62aafb..4247a8cbb 100644 --- a/test/perf/benchmarks/BenchmarksV3LocalRepo.cs +++ b/test/perf/benchmarks/BenchmarksV3LocalRepo.cs @@ -30,7 +30,7 @@ public void GlobalSetup() pwsh.Invoke(); } - + [GlobalCleanup] public void GlobalCleanup() { diff --git a/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs b/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs index 278dd7535..545b74c66 100644 --- a/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs +++ b/test/perf/benchmarks/BenchmarksV3RemoteRepo.cs @@ -21,12 +21,12 @@ public void GlobalSetup() var defaultSS = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault2(); defaultSS.ExecutionPolicy = ExecutionPolicy.Unrestricted; pwsh = System.Management.Automation.PowerShell.Create(defaultSS); - + // Import the PSGet version we want to test pwsh.AddScript("Import-Module PowerShellGet -RequiredVersion 3.0.14 -Force"); pwsh.Invoke(); } - + [GlobalCleanup] public void GlobalCleanup() { diff --git a/test/perf/benchmarks/README.md b/test/perf/benchmarks/README.md index 10c4e7835..ed765d36f 100644 --- a/test/perf/benchmarks/README.md +++ b/test/perf/benchmarks/README.md @@ -5,28 +5,33 @@ This folder contains micro benchmarks that test the performance of PSResourceGet ### Quick Start You can run the benchmarks directly using `dotnet run` in this directory: + 1. To run the benchmarks in Interactive Mode, where you will be asked which benchmark(s) to run: + ``` dotnet run -c Release -f net6.0 ``` 2. To list all available benchmarks ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Listing-the-Benchmarks)): + ``` dotnet run -c Release -f net6.0 --list [flat/tree] ``` 3. To filter the benchmarks using a glob pattern applied to `namespace.typeName.methodName` ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Filtering-the-Benchmarks)]): + ``` dotnet run -c Release -f net6.0 --filter *script* --list flat ``` 4. To profile the benchmarked code and produce an ETW Trace file ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Profiling)) + ``` dotnet run -c Release -f net6.0 --filter *script* --profiler ETW ``` - + ## References - [Getting started with BenchmarkDotNet](https://benchmarkdotnet.org/articles/guides/getting-started.html) - [Micro-benchmark Design Guidelines](https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md) -- [Adam SITNIK: Powerful benchmarking in .NET](https://www.youtube.com/watch?v=pdcrSG4tOLI&t=351s) \ No newline at end of file +- [Adam SITNIK: Powerful benchmarking in .NET](https://www.youtube.com/watch?v=pdcrSG4tOLI&t=351s) diff --git a/test/perf/benchmarks/benchmarks.csproj b/test/perf/benchmarks/benchmarks.csproj index d34e3f9b2..40d52bcb5 100644 --- a/test/perf/benchmarks/benchmarks.csproj +++ b/test/perf/benchmarks/benchmarks.csproj @@ -14,12 +14,13 @@ - + - - + + + diff --git a/test/testFiles/testModules/incorrectdepmoduleversion/incorrectdepmoduleversion.psd1 b/test/testFiles/testModules/incorrectdepmoduleversion/incorrectdepmoduleversion.psd1 index 54bd102c8..12ef9504b 100644 --- a/test/testFiles/testModules/incorrectdepmoduleversion/incorrectdepmoduleversion.psd1 +++ b/test/testFiles/testModules/incorrectdepmoduleversion/incorrectdepmoduleversion.psd1 @@ -10,123 +10,122 @@ # Script module or binary module file associated with this manifest. # RootModule = '' - + # Version number of this module. - ModuleVersion = '1.0.0.0' - + ModuleVersion = '1.0.0.0' + # Supported PSEditions # CompatiblePSEditions = @() - + # ID used to uniquely identify this module - GUID = '4f56ed2b-72af-4c29-bda6-ef3dc91c1624' - + GUID = '4f56ed2b-72af-4c29-bda6-ef3dc91c1624' + # Author of this module - Author = 'americks' - + Author = 'americks' + # Company or vendor of this module - CompanyName = 'Unknown' - + CompanyName = 'Unknown' + # Copyright statement for this module - Copyright = '(c) americks. All rights reserved.' - + Copyright = '(c) americks. All rights reserved.' + # Description of the functionality provided by this module - Description = 'incorrectdepmoduleversion module' - + Description = 'incorrectdepmoduleversion module' + # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '' - + # Name of the PowerShell host required by this module # PowerShellHostName = '' - + # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' - + # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' - + # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' - + # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' - + # Modules that must be imported into the global environment prior to importing this module - RequiredModules = @(@{ModuleName = 'PackageManagement'; ModuleVersion = '1..0.0'; }) - + RequiredModules = @(@{ModuleName = 'PackageManagement'; ModuleVersion = '1..0.0'; }) + # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() - + # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() - + # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() - + # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() - + # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() - + # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = '*' - + # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. - CmdletsToExport = '*' - + CmdletsToExport = '*' + # Variables to export from this module VariablesToExport = '*' - + # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = '*' - + AliasesToExport = '*' + # DSC resources to export from this module # DscResourcesToExport = @() - + # List of all modules packaged with this module # ModuleList = @() - + # List of all files packaged with this module # FileList = @() - + # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. - PrivateData = @{ - + PrivateData = @{ + PSData = @{ - + # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() - + # A URL to the license for this module. # LicenseUri = '' - + # A URL to the main website for this project. # ProjectUri = '' - + # A URL to an icon representing this module. # IconUri = '' - + # ReleaseNotes of this module # ReleaseNotes = '' - + # Prerelease string of this module # Prerelease = '' - + # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false - + # External dependent modules of this module # ExternalModuleDependencies = @() - + } # End of PSData hashtable - + } # End of PrivateData hashtable - + # HelpInfo URI of this module # HelpInfoURI = '' - + # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' - - } - \ No newline at end of file + +} diff --git a/test/testFiles/testModules/incorrectmoduleversion/incorrectmoduleversion.psd1 b/test/testFiles/testModules/incorrectmoduleversion/incorrectmoduleversion.psd1 index 864acb695..4ec24c35f 100644 --- a/test/testFiles/testModules/incorrectmoduleversion/incorrectmoduleversion.psd1 +++ b/test/testFiles/testModules/incorrectmoduleversion/incorrectmoduleversion.psd1 @@ -8,125 +8,125 @@ @{ -# Script module or binary module file associated with this manifest. -# RootModule = '' + # Script module or binary module file associated with this manifest. + # RootModule = '' -# Version number of this module. -ModuleVersion = '1..0.0' + # Version number of this module. + ModuleVersion = '1..0.0' -# Supported PSEditions -# CompatiblePSEditions = @() + # Supported PSEditions + # CompatiblePSEditions = @() -# ID used to uniquely identify this module -GUID = '4f56ed2b-72af-4c29-bda6-ef3dc91c1604' + # ID used to uniquely identify this module + GUID = '4f56ed2b-72af-4c29-bda6-ef3dc91c1604' -# Author of this module -Author = 'americks' + # Author of this module + Author = 'americks' -# Company or vendor of this module -CompanyName = 'Unknown' + # Company or vendor of this module + CompanyName = 'Unknown' -# Copyright statement for this module -Copyright = '(c) americks. All rights reserved.' + # Copyright statement for this module + Copyright = '(c) americks. All rights reserved.' -# Description of the functionality provided by this module -Description = 'incorrectmoduleversion module' + # Description of the functionality provided by this module + Description = 'incorrectmoduleversion module' -# Minimum version of the PowerShell engine required by this module -# PowerShellVersion = '' + # Minimum version of the PowerShell engine required by this module + # PowerShellVersion = '' -# Name of the PowerShell host required by this module -# PowerShellHostName = '' + # Name of the PowerShell host required by this module + # PowerShellHostName = '' -# Minimum version of the PowerShell host required by this module -# PowerShellHostVersion = '' + # Minimum version of the PowerShell host required by this module + # PowerShellHostVersion = '' -# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. -# DotNetFrameworkVersion = '' + # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + # DotNetFrameworkVersion = '' -# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. -# ClrVersion = '' + # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. + # ClrVersion = '' -# Processor architecture (None, X86, Amd64) required by this module -# ProcessorArchitecture = '' + # Processor architecture (None, X86, Amd64) required by this module + # ProcessorArchitecture = '' -# Modules that must be imported into the global environment prior to importing this module -RequiredModules = @(@{ModuleName = 'PackageManagement'; ModuleVersion = '1.0.0.0'; }) + # Modules that must be imported into the global environment prior to importing this module + RequiredModules = @(@{ModuleName = 'PackageManagement'; ModuleVersion = '1.0.0.0'; }) -# Assemblies that must be loaded prior to importing this module -# RequiredAssemblies = @() + # Assemblies that must be loaded prior to importing this module + # RequiredAssemblies = @() -# Script files (.ps1) that are run in the caller's environment prior to importing this module. -# ScriptsToProcess = @() + # Script files (.ps1) that are run in the caller's environment prior to importing this module. + # ScriptsToProcess = @() -# Type files (.ps1xml) to be loaded when importing this module -# TypesToProcess = @() + # Type files (.ps1xml) to be loaded when importing this module + # TypesToProcess = @() -# Format files (.ps1xml) to be loaded when importing this module -# FormatsToProcess = @() + # Format files (.ps1xml) to be loaded when importing this module + # FormatsToProcess = @() -# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess -# NestedModules = @() + # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess + # NestedModules = @() -# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. -FunctionsToExport = '*' + # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. + FunctionsToExport = '*' -# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. -CmdletsToExport = '*' + # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. + CmdletsToExport = '*' -# Variables to export from this module -VariablesToExport = '*' + # Variables to export from this module + VariablesToExport = '*' -# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. -AliasesToExport = '*' + # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. + AliasesToExport = '*' -# DSC resources to export from this module -# DscResourcesToExport = @() + # DSC resources to export from this module + # DscResourcesToExport = @() -# List of all modules packaged with this module -# ModuleList = @() + # List of all modules packaged with this module + # ModuleList = @() -# List of all files packaged with this module -# FileList = @() + # List of all files packaged with this module + # FileList = @() -# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. -PrivateData = @{ + # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. + PrivateData = @{ - PSData = @{ + PSData = @{ - # Tags applied to this module. These help with module discovery in online galleries. - # Tags = @() + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() - # A URL to the license for this module. - # LicenseUri = '' + # A URL to the license for this module. + # LicenseUri = '' - # A URL to the main website for this project. - # ProjectUri = '' + # A URL to the main website for this project. + # ProjectUri = '' - # A URL to an icon representing this module. - # IconUri = '' + # A URL to an icon representing this module. + # IconUri = '' - # ReleaseNotes of this module - # ReleaseNotes = '' + # ReleaseNotes of this module + # ReleaseNotes = '' - # Prerelease string of this module - # Prerelease = '' + # Prerelease string of this module + # Prerelease = '' - # Flag to indicate whether the module requires explicit user acceptance for install/update/save - # RequireLicenseAcceptance = $false + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false - # External dependent modules of this module - # ExternalModuleDependencies = @() + # External dependent modules of this module + # ExternalModuleDependencies = @() - } # End of PSData hashtable + } # End of PSData hashtable -} # End of PrivateData hashtable + } # End of PrivateData hashtable -# HelpInfo URI of this module -# HelpInfoURI = '' + # HelpInfo URI of this module + # HelpInfoURI = '' -# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. -# DefaultCommandPrefix = '' + # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. + # DefaultCommandPrefix = '' } diff --git a/tool/releaseTools.psm1 b/tool/releaseTools.psm1 index 1e1b6a9bf..d6a006666 100644 --- a/tool/releaseTools.psm1 +++ b/tool/releaseTools.psm1 @@ -35,7 +35,7 @@ function Get-Bullet { [Parameter(Mandatory, ValueFromPipeline)] [PSCustomObject]$PullRequest ) - ("-", $PullRequest.title, ("(#" + $PullRequest.PullRequestNumber + ")") -join " ").Trim() + ("-", $PullRequest.title, ("(#" + $PullRequest.PullRequestNumber + ")") -join " ").Trim() } <# @@ -45,18 +45,20 @@ function Get-Bullet { Uses the local Git repositories but does not pull, so ensure HEAD is where you want it. #> -function Get-Changelog { +function Get-Changelog { # This will take some time because it has to pull all PRs and then filter - $script:PullRequests = $script:Repo | Get-GitHubPullRequest -State 'closed' | - Where-Object { $_.labels.LabelName -match 'Release' } | - Where-Object { -not $_.title.StartsWith("[WIP]") } | - Where-Object { -not $_.title.StartsWith("WIP") } + $script:PullRequests = $script:Repo | + Get-GitHubPullRequest -State 'closed' | + Where-Object -FilterScript { + $_.labels.LabelName -match 'Release' -and + -not $_.title.StartsWith("[WIP]") -and + -not $_.title.StartsWith("WIP") + } $PullRequests | ForEach-Object { if ($_.labels.LabelName -match 'PR-Bug') { $script:BugFixes += Get-Bullet($_) - } - else { + } else { $script:NewFeatures += Get-Bullet($_) } } @@ -114,7 +116,7 @@ function Update-PSDFile { [string]$Version ) $CurrentPSDFile = Get-Content -Path ".\src\PSResourceGet.psd1" - $Header = $CurrentPSDFile.Where({$_.StartsWith("## ")}, "First") + $Header = $CurrentPSDFile.Where({ $_.StartsWith("## ") }, "First") @( $CurrentPSDFile.Where({ $_ -eq $Header }, "Until") @@ -153,11 +155,11 @@ function New-ReleasePR { } $Params = @{ - Head = "$($Username):release" - Base = "master" + Head = "$($Username):release" + Base = "master" Draft = $true Title = "Update CHANGELOG for ``$Version``" - Body = "An automated PR to update the CHANGELOG.md file for a new release" + Body = "An automated PR to update the CHANGELOG.md file for a new release" } $PR = $script:Repo | New-GitHubPullRequest @Params @@ -166,7 +168,7 @@ function New-ReleasePR { <# .SYNOPSIS - Given the version and the username for the forked repository, updates the CHANGELOG.md file and creates a draft GitHub PR + Given the version and the username for the forked repository, updates the CHANGELOG.md file and creates a draft GitHub PR #> function New-Release { param( @@ -183,13 +185,13 @@ function New-Release { <# .SYNOPSIS - Removes the `Release` label after updating the CHANGELOG.md file + Removes the `Release` label after updating the CHANGELOG.md file #> function Remove-Release-Label { $script:PullRequests = $script:Repo | Get-GitHubPullRequest -State 'closed' | - Where-Object { $_.labels.LabelName -match 'Release' } | - Where-Object { -not $_.title.StartsWith("[WIP]") } | - Where-Object { -not $_.title.StartsWith("WIP") } + Where-Object { $_.labels.LabelName -match 'Release' } | + Where-Object { -not $_.title.StartsWith("[WIP]") } | + Where-Object { -not $_.title.StartsWith("WIP") } $script:PullRequests | ForEach-Object { $script:Repo | Remove-GitHubIssueLabel -Label Release -Issue $_.PullRequestNumber diff --git a/tool/setupReleaseTools.ps1 b/tool/setupReleaseTools.ps1 index a57d29e54..dd7162d66 100644 --- a/tool/setupReleaseTools.ps1 +++ b/tool/setupReleaseTools.ps1 @@ -6,9 +6,9 @@ param( [string]$Token ) -Write-Host "Install and import PowerShell modules" -Set-PSResourceRepository -Name PSGallery -Trusted | Out-Null -Install-Module -Name PowerShellForGitHub -Scope CurrentUser -Force +Write-Host 'Install and import PowerShell modules' +$null = Set-PSResourceRepository -Name PSGallery -Trusted +Install-PSResource -Repository 'PSGallery' -Name 'PowerShellForGitHub' -Scope 'CurrentUser' -Force Import-Module $PSScriptRoot/releaseTools.psm1 Write-Host "Setup authentication"