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..7dcad03a0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,11 @@ +**/BenchmarkDotNet.Artifacts/ +.vs +out +src/code/.vs src/code/bin src/code/obj srcOld/code/bin srcOld/code/obj -out -test/**/obj test/**/bin -.vs -.vscode -src/code/.vs -test/testFiles/testScripts/test.ps1 \ No newline at end of file +test/**/obj +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..342f43b45 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,19 @@ { - "csharp.semanticHighlighting.enabled": true, - "dotnet.automaticallyCreateSolutionInWorkspace": false, - "omnisharp.enableEditorConfigSupport": true, - "omnisharp.enableRoslynAnalyzers": true + "[csharp]": { + "editor.defaultFormatter": "ms-dotnettools.csharp" + }, + "[powershell]": { + "editor.defaultFormatter": "ms-vscode.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/Examples/FindRepositorySearchingExamples.md b/Examples/FindRepositorySearchingExamples.md index 6bc4dd1c8..b991495e9 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,87 +17,109 @@ 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'. ``` @@ -105,15 +127,18 @@ Note that PSGallery has a lower priority than 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'. + Should return 'TestModule' from 'PSGallery'. * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -132,10 +158,11 @@ 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'. + 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'. @@ -144,6 +171,7 @@ Note that PSGallery has a lower priority than 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,12 +221,14 @@ 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: @@ -203,27 +240,33 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. 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,11 +274,13 @@ 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: @@ -247,31 +292,38 @@ In these examples, the package TestModule has the following tags: Tag1, Tag2. 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,12 +331,14 @@ 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: @@ -297,15 +351,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 +370,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'. + Should return 'TestModule' from 'PSGallery'. * When the package exists the second repository (NuGetGallery), but not the first (PSGallery): + ``` Name Version Prerelease Repository ---- ------- ---------- ---------- @@ -324,10 +382,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'. + 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,12 +395,14 @@ 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: @@ -354,6 +415,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,41 +426,51 @@ 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. @@ -411,27 +483,33 @@ In these examples, the package TestModule has the following command names (i.e t 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,11 +517,13 @@ 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: @@ -455,28 +535,35 @@ In these examples, the package TestModule has the following command names (i.e t 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,11 +571,13 @@ 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: @@ -501,14 +590,17 @@ In these examples, the package TestModule has the following command names (i.e t 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 +608,29 @@ 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. + 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,8 +638,8 @@ 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: @@ -552,11 +648,13 @@ In these examples, the package TestModule has the following command names (i.e t 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,41 +665,51 @@ 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. @@ -614,27 +722,33 @@ In these examples, the package TestModule has the following DscResource names (i 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,11 +756,13 @@ 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: @@ -658,28 +774,35 @@ In these examples, the package TestModule has the following DscResource names (i 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,11 +810,13 @@ 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: @@ -704,14 +829,17 @@ In these examples, the package TestModule has the following DscResource names (i 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 +847,29 @@ 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. + 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,8 +877,8 @@ 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: @@ -755,11 +887,13 @@ In these examples, the package TestModule has the following DscResource names (i 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. ``` 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/bootstrap.ps1 b/bootstrap.ps1 index ab2e16968..2f48bc550 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -9,16 +9,14 @@ try { $IsLinux = $Runtime::IsOSPlatform($OSPlatform::Linux) $IsMacOS = $Runtime::IsOSPlatform($OSPlatform::OSX) $IsWindows = $Runtime::IsOSPlatform($OSPlatform::Windows) -} -catch { +} catch { # If these are already set, then they're read-only and we're done try { $IsCoreCLR = $false $IsLinux = $false $IsMacOS = $false $IsWindows = $true - } - catch { } + } catch { } } if ($IsLinux) { @@ -33,75 +31,71 @@ if ($IsLinux) { function Start-DotnetBootstrap { [CmdletBinding( SupportsShouldProcess = $true, - ConfirmImpact = "High")] + ConfirmImpact = 'High')] param( - [string]$Channel = "preview", + [string]$Channel = 'preview', #[string]$Version = "latest", # we currently pin dotnet-cli version, because tool # is currently migrating to msbuild toolchain # and requires constant updates to our build process. - [string]$Version = "2.1.503" + [string]$Version = '2.1.503' ) # Install ours and .NET's dependencies $Deps = @() if ($IsUbuntu) { # Build tools - $Deps += "curl", "g++", "cmake", "make" + $Deps += 'curl', 'g++', 'cmake', 'make' # .NET Core required runtime libraries - $Deps += "libunwind8" - if ($IsUbuntu14) { $Deps += "libicu52" } - elseif ($IsUbuntu16) { $Deps += "libicu55" } + $Deps += 'libunwind8' + if ($IsUbuntu14) { $Deps += 'libicu52' } + elseif ($IsUbuntu16) { $Deps += 'libicu55' } # Install dependencies sudo apt-get install -y -qq $Deps - } - elseif ($IsCentOS) { + } elseif ($IsCentOS) { # Build tools - $Deps += "which", "curl", "gcc-c++", "cmake", "make" + $Deps += 'which', 'curl', 'gcc-c++', 'cmake', 'make' # .NET Core required runtime libraries - $Deps += "libicu", "libunwind" + $Deps += 'libicu', 'libunwind' # Install dependencies sudo yum install -y -q $Deps - } - elseif ($IsMacOS) { + } elseif ($IsMacOS) { # Build tools - $Deps += "curl", "cmake" + $Deps += 'curl', 'cmake' # .NET Core required runtime libraries - $Deps += "openssl" + $Deps += 'openssl' # Install dependencies brew install $Deps } - $obtainUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain" + $obtainUrl = 'https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain' # Install for Linux and OS X if ($IsLinux -or $IsMacOS) { # Uninstall all previous dotnet packages $uninstallScript = if ($IsUbuntu) { - "dotnet-uninstall-debian-packages.sh" - } - elseif ($IsMacOS) { - "dotnet-uninstall-pkgs.sh" + 'dotnet-uninstall-debian-packages.sh' + } elseif ($IsMacOS) { + 'dotnet-uninstall-pkgs.sh' } if ($uninstallScript) { curl -s $obtainUrl/uninstall/$uninstallScript -o $uninstallScript chmod +x $uninstallScript sudo ./$uninstallScript - } - else { - Write-Warning "This script only removes prior versions of dotnet for Ubuntu 14.04 and OS X" + } else { + Write-Warning 'This script only removes prior versions of dotnet for Ubuntu 14.04 and OS X' } # Install new dotnet 1.0.0 preview packages - $installScript = "dotnet-install.sh" + $installScript = 'dotnet-install.sh' curl -s $obtainUrl/$installScript -o $installScript chmod +x $installScript bash ./$installScript -c $Channel -v $Version @@ -110,7 +104,7 @@ function Start-DotnetBootstrap { if ($IsMacOS) { # This is the library shipped with .NET Core # This is allowed to fail as the user may have installed other versions of dotnet - Write-Warning ".NET Core links the incorrect OpenSSL, correcting .NET CLI libraries..." + Write-Warning '.NET Core links the incorrect OpenSSL, correcting .NET CLI libraries...' find $env:HOME/.dotnet -name System.Security.Cryptography.Native.dylib | xargs sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib } } @@ -118,7 +112,7 @@ function Start-DotnetBootstrap { # Install for Windows if ($IsWindows) { Remove-Item -ErrorAction SilentlyContinue -Recurse -Force ~\AppData\Local\Microsoft\dotnet - $installScript = "dotnet-install.ps1" + $installScript = 'dotnet-install.ps1' Invoke-WebRequest -Uri $obtainUrl/$installScript -OutFile $installScript & ./$installScript -c $Channel -Version $Version } diff --git a/build.ps1 b/build.ps1 index 68de8f552..2384d71de 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,30 +1,30 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] -[CmdletBinding(DefaultParameterSetName="build")] +[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '')] +[CmdletBinding(DefaultParameterSetName = 'build')] param ( - [Parameter(ParameterSetName="build")] + [Parameter(ParameterSetName = 'build')] [switch] $Clean, - [Parameter(ParameterSetName="build")] + [Parameter(ParameterSetName = 'build')] [switch] $Build, - [Parameter(ParameterSetName="publish")] + [Parameter(ParameterSetName = 'publish')] [switch] $Publish, - [Parameter(ParameterSetName="publish")] + [Parameter(ParameterSetName = 'publish')] [switch] $Signed, - [ValidateSet("Debug", "Release")] - [string] $BuildConfiguration = "Debug", + [ValidateSet('Debug', 'Release')] + [string] $BuildConfiguration = 'Debug', - [ValidateSet("net472")] - [string] $BuildFramework = "net472" + [ValidateSet('net472')] + [string] $BuildFramework = 'net472' ) Import-Module -Name "$PSScriptRoot/buildtools.psd1" -Force @@ -46,11 +46,11 @@ $script:BuildFramework = $BuildFramework if ($env:TF_BUILD) { $vstsCommandString = "vso[task.setvariable variable=BUILD_OUTPUT_PATH]$OutDirectory" - Write-Host ("sending " + $vstsCommandString) + Write-Host ('sending ' + $vstsCommandString) Write-Host "##$vstsCommandString" $vstsCommandString = "vso[task.setvariable variable=SIGNED_OUTPUT_PATH]$SignedDirectory" - Write-Host ("sending " + $vstsCommandString) + Write-Host ('sending ' + $vstsCommandString) Write-Host "##$vstsCommandString" } @@ -61,33 +61,26 @@ if ($Clean) { Remove-Item -Path $OutDirectory -Force -Recurse -ErrorAction Stop -Verbose } - if (Test-Path "${SrcPath}/code/bin") - { + if (Test-Path "${SrcPath}/code/bin") { Remove-Item -Path "${SrcPath}/code/bin" -Recurse -Force -ErrorAction Stop -Verbose } - if (Test-Path "${SrcPath}/code/obj") - { + if (Test-Path "${SrcPath}/code/obj") { Remove-Item -Path "${SrcPath}/code/obj" -Recurse -Force -ErrorAction Stop -Verbose } } -if (-not (Test-Path $OutDirectory)) -{ +if (-not (Test-Path $OutDirectory)) { $script:OutModule = New-Item -ItemType Directory -Path (Join-Path $OutDirectory $ModuleName) -} -else -{ +} else { $script:OutModule = Join-Path $OutDirectory $ModuleName } -if ($Build.IsPresent -or $PsCmdlet.ParameterSetName -eq "Build") -{ +if ($Build.IsPresent -or $PsCmdlet.ParameterSetName -eq 'Build') { $sb = (Get-Item Function:DoBuild).ScriptBlock Invoke-ModuleBuild -BuildScript $sb } -if ($Publish.IsPresent) -{ +if ($Publish.IsPresent) { Publish-ModulePackage -Signed:$Signed.IsPresent } diff --git a/buildtools.psd1 b/buildtools.psd1 index ca69ed311..60a6ba2d1 100644 --- a/buildtools.psd1 +++ b/buildtools.psd1 @@ -3,28 +3,28 @@ @{ # Script module or binary module file associated with this manifest. - RootModule = '.\buildtools.psm1' + RootModule = '.\buildtools.psm1' # Version number of this module. - ModuleVersion = '1.0.0' + ModuleVersion = '1.0.0' # Supported PSEditions CompatiblePSEditions = @('Core') # ID used to uniquely identify this module - GUID = 'fcdd259e-1163-4da2-8bfa-ce36a839f337' + GUID = 'fcdd259e-1163-4da2-8bfa-ce36a839f337' # Author of this module - Author = 'Microsoft Corporation' + Author = 'Microsoft Corporation' # Company or vendor of this module - CompanyName = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' # Copyright statement for this module - Copyright = '(c) Microsoft Corporation. All rights reserved.' + Copyright = '(c) Microsoft Corporation. All rights reserved.' # Description of the functionality provided by this module - Description = "Build utilities." + Description = 'Build utilties.' # Modules that must be imported into the global environment prior to importing this module #RequiredModules = @( @@ -34,18 +34,18 @@ #) # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '5.1' + PowerShellVersion = '5.1' # 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 = @() # 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 = @( + FunctionsToExport = @( 'Get-BuildConfiguration', 'Invoke-ModuleBuild', 'Publish-ModulePackage', 'Install-ModulePackageForTest', 'Invoke-ModuleTests', 'Invoke-ModuleTestsACR') # Variables to export from this module - VariablesToExport = '*' + 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 = @() } diff --git a/buildtools.psm1 b/buildtools.psm1 index 9aab19832..a0f40d172 100644 --- a/buildtools.psm1 +++ b/buildtools.psm1 @@ -15,8 +15,7 @@ function Get-BuildConfiguration { if (Test-Path $resolvedPath -PathType Container) { $fileNamePath = Join-Path -Path $resolvedPath -ChildPath $ConfigurationFileName - } - else { + } else { $fileName = Split-Path -Path $resolvedPath -Leaf if ($fileName -ne $ConfigurationFileName) { throw "$ConfigurationFileName not found in provided pathname: $resolvedPath" @@ -24,7 +23,7 @@ function Get-BuildConfiguration { $fileNamePath = $resolvedPath } - if (! (Test-Path -Path $fileNamePath -PathType Leaf)) { + if (-not (Test-Path -Path $fileNamePath -PathType Leaf)) { throw "$ConfigurationFileName not found at path: $resolvedPath" } @@ -37,8 +36,7 @@ function Get-BuildConfiguration { $configObj.BuildOutputPath = Join-Path $projectRoot -ChildPath $configObj.BuildOutputPath if ($configObj.SignedOutputPath) { $configObj.SignedOutputPath = Join-Path $projectRoot -ChildPath $configObj.SignedOutputPath - } - else { + } else { $configObj | Add-Member -MemberType NoteProperty -Name SignedOutputPath -Value (Join-Path $projectRoot -ChildPath 'signed') } @@ -48,26 +46,32 @@ function Get-BuildConfiguration { function Invoke-ModuleBuild { [CmdletBinding()] param ( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [ScriptBlock] $BuildScript ) - Write-Verbose -Verbose -Message "Invoking build script" + Write-Verbose -Verbose -Message 'Invoking build script' + + #$BuildScript.Invoke() + $result = Invoke-Command -ScriptBlock $BuildScript - $BuildScript.Invoke() + if ($result.Error.Count -gt 0) { + throw "Error occurred during build: $($result.Error)" + } + + $result.Output | ForEach-Object { Write-Output $_ } - Write-Verbose -Verbose -Message "Finished invoking build script" + Write-Verbose -Verbose -Message 'Finished invoking build script' } -function Publish-ModulePackage -{ +function Publish-ModulePackage { [CmdletBinding()] param ( [Parameter()] [Switch] $Signed ) - Write-Verbose -Verbose -Message "Creating new local package repo" + Write-Verbose -Verbose -Message 'Creating new local package repo' $localRepoName = 'packagebuild-local-repo' $localRepoLocation = Join-Path -Path ([System.io.path]::GetTempPath()) -ChildPath $localRepoName if (Test-Path -Path $localRepoLocation) { @@ -80,7 +84,7 @@ function Publish-ModulePackage Write-Verbose -Verbose -Message "Publishing package to local repo: $localRepoName" $config = Get-BuildConfiguration - if (! $Signed.IsPresent) { + if (-not $Signed.IsPresent) { $modulePath = Join-Path -Path $config.BuildOutputPath -ChildPath $config.ModuleName } else { $modulePath = Join-Path -Path $config.SignedOutputPath -ChildPath $config.ModuleName @@ -88,8 +92,8 @@ function Publish-ModulePackage Publish-PSResource -Path $modulePath -Repository $localRepoName -SkipDependenciesCheck -Confirm:$false -Verbose if ($env:TF_BUILD) { - Write-Verbose -Verbose -Message "Uploading module nuget package artifact to AzDevOps" - $artifactName = "nupkg" + Write-Verbose -Verbose -Message 'Uploading module nuget package artifact to AzDevOps' + $artifactName = 'nupkg' $artifactPath = (Get-ChildItem -Path $localRepoLocation -Filter "$($config.ModuleName)*.nupkg").FullName $artifactPath = Resolve-Path -Path $artifactPath Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$artifactPath" @@ -102,36 +106,36 @@ function Publish-ModulePackage function Install-ModulePackageForTest { [CmdletBinding()] param ( - [Parameter(Mandatory=$true)] + [Parameter(Mandatory = $true)] [string] $PackagePath ) $config = Get-BuildConfiguration $localRepoName = 'packagebuild-local-repo' - $packagePathWithNupkg = Join-Path -Path $PackagePath -ChildPath "nupkg" + $packagePathWithNupkg = Join-Path -Path $PackagePath -ChildPath 'nupkg' Write-Verbose -Verbose -Message "Registering local package repo: $localRepoName to path: $packagePathWithNupkg" Register-PSResourceRepository -Name $localRepoName -Uri $packagePathWithNupkg -Trusted -Force $installationPath = $config.BuildOutputPath - if ( !(Test-Path $installationPath)) { + if (-not (Test-Path -Path $installationPath)) { Write-Verbose -Verbose -Message "Creating module directory location for tests: $installationPath" $null = New-Item -Path $installationPath -ItemType Directory -Verbose } Write-Verbose -Verbose -Message "Installing module $($config.ModuleName) to build output path $installationPath" - $psgetModuleBase = (get-command save-psresource).Module.ModuleBase - $psgetVersion = (get-command save-psresource).Module.Version.ToString() - $psgetPrerelease = (get-command find-psresource).module.PrivateData.PSData.Prerelease + $psgetModuleBase = (Get-Command save-psresource).Module.ModuleBase + $psgetVersion = (Get-Command save-psresource).Module.Version.ToString() + $psgetPrerelease = (Get-Command find-psresource).module.PrivateData.PSData.Prerelease Write-Verbose -Verbose -Message "PSResourceGet module base imported: $psgetModuleBase" Write-Verbose -Verbose -Message "PSResourceGet version base imported: $psgetVersion" Write-Verbose -Verbose -Message "PSResourceGet prerelease base imported: $psgetPrerelease" #Save-PSResource -Name $config.ModuleName -Repository $localRepoName -Path $installationPath -SkipDependencyCheck -Prerelease -Confirm:$false -TrustRepository Register-PSRepository -Name $localRepoName -SourceLocation $packagePathWithNupkg -InstallationPolicy Trusted -Verbose - $psgetv2ModuleBase = (get-command save-module).Module.ModuleBase - $psgetv2Version = (get-command save-module).Module.Version.ToString() - $psgetv2Prerelease = (get-command save-module).module.PrivateData.PSData.Prerelease + $psgetv2ModuleBase = (Get-Command save-module).Module.ModuleBase + $psgetv2Version = (Get-Command save-module).Module.Version.ToString() + $psgetv2Prerelease = (Get-Command save-module).module.PrivateData.PSData.Prerelease Write-Verbose -Verbose -Message "PowerShellGet module base imported: $psgetv2ModuleBase" Write-Verbose -Verbose -Message "PowerShellGet version base imported: $psgetv2Version" Write-Verbose -Verbose -Message "PowerShellGet prerelease base imported: $psgetv2Prerelease" @@ -145,14 +149,14 @@ function Install-ModulePackageForTest { function Invoke-ModuleTestsACR { [CmdletBinding()] param ( - [ValidateSet("Functional", "StaticAnalysis")] - [string[]] $Type = "Functional" + [ValidateSet('Functional', 'StaticAnalysis')] + [string[]] $Type = 'Functional' ) $acrTestFiles = @( - "FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1", - "InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1", - "PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1" + 'FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1', + 'InstallPSResourceTests/InstallPSResourceContainerRegistryServer.Tests.ps1', + 'PublishPSResourceTests/PublishPSResourceContainerRegistryServer.Tests.ps1' ) Invoke-ModuleTests -Type $Type -TestFilePath $acrTestFiles @@ -162,12 +166,12 @@ function Invoke-ModuleTestsACR { function Invoke-ModuleTests { [CmdletBinding()] param ( - [ValidateSet("Functional", "StaticAnalysis")] - [string[]] $Type = "Functional", - [string[]] $TestFilePath = "." + [ValidateSet('Functional', 'StaticAnalysis')] + [string[]] $Type = 'Functional', + [string[]] $TestFilePath = '.' ) - Write-Verbose -Verbose -Message "Starting module Pester tests..." + Write-Verbose -Verbose -Message 'Starting module Pester tests...' # Run module Pester tests. $config = Get-BuildConfiguration @@ -175,13 +179,12 @@ function Invoke-ModuleTests { $excludeTag = 'ManualValidationOnly' $testResultFileName = 'result.pester.xml' $testPath = $config.TestPath - Write-Verbose -Verbose $config.ModuleName - $moduleToTest = Join-Path -Path $config.BuildOutputPath -ChildPath "Microsoft.PowerShell.PSResourceGet" + Write-Verbose -Verbose -Message $config.ModuleName + $moduleToTest = Join-Path -Path $config.BuildOutputPath -ChildPath 'Microsoft.PowerShell.PSResourceGet' if ($TestFilePath.Count -gt 1) { $TestFilePathJoined = $TestFilePath -join ',' - } - else { + } else { $TestFilePathJoined = $TestFilePath } @@ -192,9 +195,8 @@ function Invoke-ModuleTests { try { & $pwshExePath -NoProfile -NoLogo -Command $command - } - catch { - Write-Error -Message "Error invoking module Pester tests." + } catch { + Write-Error -Message 'Error invoking module Pester tests.' } $testResultsFilePath = Join-Path -Path $testPath -ChildPath $testResultFileName @@ -203,7 +205,7 @@ function Invoke-ModuleTests { # and class it references to do so can't be found. This will be fixed later. # # Examine Pester test results. - # if (! (Test-Path -Path $testResultsFilePath)) { + # if (-not (Test-Path -Path $testResultsFilePath)) { # throw "Module test result file not found: '$testResultsFilePath'" # } # $xmlDoc = [xml] (Get-Content -Path $testResultsFilePath -Raw) @@ -219,7 +221,7 @@ function Invoke-ModuleTests { # Publish test results to AzDevOps if ($env:TF_BUILD) { - Write-Verbose -Verbose -Message "Uploading test results to AzDevOps" + Write-Verbose -Verbose -Message 'Uploading test results to AzDevOps' $powerShellName = if ($PSVersionTable.PSEdition -eq 'Core') { 'PowerShell Core' } else { 'Windows PowerShell' } $TestType = 'NUnit' $Title = "Functional Tests - $env:AGENT_OS - $powershellName Results" @@ -229,7 +231,7 @@ function Invoke-ModuleTests { Write-Host "##$message" } - Write-Verbose -Verbose -Message "Module Pester tests complete." + Write-Verbose -Verbose -Message 'Module Pester tests complete.' } function Show-PSPesterError { @@ -242,9 +244,9 @@ function Show-PSPesterError { $description = $testFailure.description $name = $testFailure.name $message = $testFailure.failure.message - $stackTrace = $testFailure.failure."stack-trace" + $stackTrace = $testFailure.failure.'stack-trace' - $fullMsg = "`n{0}`n{1}`n{2}`n{3}`{4}" -f ("Description: " + $description), ("Name: " + $name), "message:", $message, "stack-trace:", $stackTrace + $fullMsg = "`n{0}`n{1}`n{2}`n{3}`{4}" -f ('Description: ' + $description), ('Name: ' + $name), 'message:', $message, 'stack-trace:', $stackTrace Write-Error $fullMsg } diff --git a/doBuild.ps1 b/doBuild.ps1 index 15293d99b..e03562d22 100644 --- a/doBuild.ps1 +++ b/doBuild.ps1 @@ -5,50 +5,41 @@ .DESCRIPTION Implement build and packaging of the package and place the output $OutDirectory/$ModuleName #> -function DoBuild -{ - Write-Verbose -Verbose -Message "Starting DoBuild for $ModuleName with configuration: $BuildConfiguration, framework: $BuildFramework" +function DoBuild { + Write-Verbose -Verbose -Message "Starting DoBuild for $ModuleName with configuration: $BuildConfiguration, framework: $BuildFramework" # Module build out path - $BuildOutPath = "${OutDirectory}/${ModuleName}" + $BuildOutPath = [System.IO.Path]::Combine($OutDirectory, $ModuleName) Write-Verbose -Verbose -Message "Module output file path: '$BuildOutPath'" # Module build source path - $BuildSrcPath = "bin/${BuildConfiguration}/${BuildFramework}/publish" + $BuildSrcPath = [System.IO.Path]::Combine($SrcPath, 'code', 'bin', $BuildConfiguration, $BuildFramework, 'publish') Write-Verbose -Verbose -Message "Module build source path: '$BuildSrcPath'" - # Copy module .psd1 file - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.psd1 to $BuildOutPath" - Copy-Item -Path "${SrcPath}/${ModuleName}.psd1" -Dest "$BuildOutPath" -Force - - # Copy module .psm1 file - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.psm1 to $BuildOutPath" - Copy-Item -Path "${SrcPath}/${ModuleName}.psm1" -Dest "$BuildOutPath" -Force - - #Copy module format ps1xml file - Write-Verbose -Verbose -Message "Copy-Item ${SrcPath}/${FormatFileName}.ps1xml to $BuildOutPath" - Copy-Item -Path "${SrcPath}/${FormatFileName}.ps1xml" -Dest "$BuildOutPath" -Force - - # Copy license - Write-Verbose -Verbose -Message "Copying LICENSE file to '$BuildOutPath'" - Copy-Item -Path "./LICENSE" -Dest "$BuildOutPath" - - # Copy notice - Write-Verbose -Verbose -Message "Copying Notice.txt to '$BuildOutPath'" - Copy-Item -Path "./Notice.txt" -Dest "$BuildOutPath" - - # Copy Group Policy files - Write-Verbose -Verbose -Message "Copying InstallPSResourceGetPolicyDefinitions.ps1 to '$BuildOutPath'" - Copy-Item -Path "${SrcPath}/InstallPSResourceGetPolicyDefinitions.ps1" -Dest "$BuildOutPath" -Force - - Write-Verbose -Verbose -Message "Copying PSResourceRepository.adml to '$BuildOutPath'" - Copy-Item -Path "${SrcPath}/PSResourceRepository.adml" -Dest "$BuildOutPath" -Force - - Write-Verbose -Verbose -Message "Copying PSResourceRepository.admx to '$BuildOutPath'" - Copy-Item -Path "${SrcPath}/PSResourceRepository.admx" -Dest "$BuildOutPath" -Force + # Copy files + $FilesToCopy = [string[]]( + # Module .psd1 file + [System.IO.Path]::Combine($SrcPath, $ModuleName + '.psd1'), + # Module .psm1 file + [System.IO.Path]::Combine($SrcPath, $ModuleName + '.psm1'), + # Module format ps1xml file + [System.IO.Path]::Combine($SrcPath, $FormatFileName + '.ps1xml'), + # License + [System.IO.Path]::Combine('.', 'LICENSE'), + # Notice + [System.IO.Path]::Combine('.', 'Notice.txt'), + # Group Policy files + [System.IO.Path]::Combine($SrcPath, 'InstallPSResourceGetPolicyDefinitions.ps1'), + [System.IO.Path]::Combine($SrcPath, 'PSResourceRepository.adml'), + [System.IO.Path]::Combine($SrcPath, 'PSResourceRepository.admx') + ) + foreach ($File in $FilesToCopy) { + Write-Verbose -Message ('Copying "{0}" to "{1}"' -f $File, $BuildOutPath) + Copy-Item -Path $File -Destination $BuildOutPath -Force + } # Build and place binaries - if ( Test-Path "${SrcPath}/code" ) { + if (Test-Path -Path "${SrcPath}/code") { Write-Verbose -Verbose -Message "Building assembly and copying to '$BuildOutPath'" # Build code and place it in the staging location Push-Location "${SrcPath}/code" @@ -58,8 +49,8 @@ function DoBuild # Check for dotnet for Windows (we only build on Windows platforms). if ($null -eq $dotnetCommand) { - Write-Verbose -Verbose -Message "dotnet.exe cannot be found in current path. Looking in ProgramFiles path." - $dotnetCommandPath = Join-Path -Path $env:ProgramFiles -ChildPath "dotnet\dotnet.exe" + Write-Verbose -Verbose -Message 'dotnet.exe cannot be found in current path. Looking in ProgramFiles path.' + $dotnetCommandPath = [System.IO.Path]::Combine($env:ProgramFiles, 'dotnet', 'dotnet.exe') $dotnetCommand = Get-Command -Name $dotnetCommandPath -ErrorAction Ignore if ($null -eq $dotnetCommand) { throw "Dotnet.exe cannot be found: $dotnetCommandPath is unavailable for build." @@ -126,12 +117,10 @@ function DoBuild $buildSuccess = $true # Copy module binaries - foreach ($fileName in $assemblyNames) - { + foreach ($fileName in $assemblyNames) { # Copy bin file $filePath = Join-Path -Path $BuildSrcPath -ChildPath "${fileName}.dll" - if (! (Test-Path -Path $filePath)) - { + if (-not (Test-Path -Path $filePath)) { Write-Error "Expected file $filePath is missing from build output." $BuildSuccess = $false continue @@ -141,13 +130,12 @@ function DoBuild # Copy pdb file if available $filePathPdb = Join-Path -Path $BuildSrcPath -ChildPath "${fileName}.pdb" - if (Test-Path -Path $filePathPdb) - { + if (Test-Path -Path $filePathPdb) { Copy-Item -Path $filePathPdb -Dest $BuildOutPath -Verbose -Force } } - $depsOutputBinPath = Join-Path -Path $BuildOutPath -ChildPath "dependencies" + $depsOutputBinPath = Join-Path -Path $BuildOutPath -ChildPath 'dependencies' if (-not (Test-Path $depsOutputBinPath)) { Write-Verbose -Verbose -Message "Creating output path for dependencies: $depsOutputBinPath" @@ -155,12 +143,10 @@ function DoBuild } # Copy dependencies - foreach ($fileName in $depAssemblyNames) - { + foreach ($fileName in $depAssemblyNames) { # Copy bin file $filePath = Join-Path -Path $BuildSrcPath -ChildPath "${fileName}.dll" - if (! (Test-Path -Path $filePath)) - { + if (-not (Test-Path -Path $filePath)) { Write-Error "Expected file $filePath is missing from build output." $BuildSuccess = $false continue @@ -169,28 +155,23 @@ function DoBuild Copy-Item -Path $filePath -Dest $depsOutputBinPath -Verbose -Force } - if (! $buildSuccess) - { - throw "Build failed to create expected binaries." + if (-not $buildSuccess) { + throw 'Build failed to create expected binaries.' } - if (! (Test-Path -Path "$BuildSrcPath/${ModuleName}.dll")) - { + if (-not (Test-Path -Path "$BuildSrcPath/${ModuleName}.dll")) { throw "Expected binary was not created: $BuildSrcPath/${ModuleName}.dll" } - } - catch { + } catch { Write-Verbose -Verbose -Message "dotnet build failed with error: $_" Write-Error "dotnet build failed with error: $_" - } - finally { + } finally { Pop-Location } - } - else { + } else { Write-Verbose -Verbose -Message "No code to build in '${SrcPath}/code'" } ## Add build and packaging here - Write-Verbose -Verbose -Message "Ending DoBuild" + Write-Verbose -Verbose -Message 'Ending DoBuild' } diff --git a/global.json b/global.json index 100631a86..566059ca8 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { - "sdk": { - "version": "8.0.414" - } + "sdk": { + "version": "8.0.414" + } } diff --git a/src/InstallPSResourceGetPolicyDefinitions.ps1 b/src/InstallPSResourceGetPolicyDefinitions.ps1 index e0f2d15d4..3b670ceab 100644 --- a/src/InstallPSResourceGetPolicyDefinitions.ps1 +++ b/src/InstallPSResourceGetPolicyDefinitions.ps1 @@ -19,31 +19,27 @@ param Set-StrictMode -Version 3.0 $ErrorActionPreference = 'Stop' -function Test-Elevated -{ +function Test-Elevated { [CmdletBinding()] [OutputType([bool])] - Param() + param() # if the current Powershell session was called with administrator privileges, # the Administrator Group's well-known SID will show up in the Groups for the current identity. # Note that the SID won't show up unless the process is elevated. - return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") + return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains 'S-1-5-32-544') } $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.' } @@ -51,14 +47,12 @@ $admxName = 'PSResourceRepository.admx' $admlName = 'PSResourceRepository.adml' $admx = Get-Item -Path (Join-Path -Path $Path -ChildPath $admxName) $adml = Get-Item -Path (Join-Path -Path $Path -ChildPath $admlName) -$admxTargetPath = Join-Path -Path $env:WINDIR -ChildPath "PolicyDefinitions" -$admlTargetPath = Join-Path -Path $admxTargetPath -ChildPath "en-US" +$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 fad665d1c..a15913c0e 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 = 'preview3' Tags = @('PackageManagement', diff --git a/src/Microsoft.PowerShell.PSResourceGet.psm1 b/src/Microsoft.PowerShell.PSResourceGet.psm1 index 3e477cb1f..6de0a8dfc 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psm1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psm1 @@ -15,11 +15,10 @@ 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" + $PSRepositoriesFilePath = Microsoft.PowerShell.Management\Join-Path -Path $PSGetAppLocalPath -ChildPath 'PSRepositories.xml' $PSGetRepositories = Microsoft.PowerShell.Utility\Import-Clixml $PSRepositoriesFilePath -ea SilentlyContinue Microsoft.PowerShell.Utility\Write-Verbose ('Found {0} registered PowerShellGet repositories.' -f $PSGetRepositories.Count) @@ -27,8 +26,8 @@ function Import-PSGetRepository { if ($PSGetRepositories.Count) { $repos = @( $PSGetRepositories.Values | - Microsoft.PowerShell.Core\Where-Object {$_.PackageManagementProvider -eq 'NuGet'-and $_.Name -ne 'PSGallery'} | - Microsoft.PowerShell.Utility\Select-Object Name, Trusted, SourceLocation + Microsoft.PowerShell.Core\Where-Object { $_.PackageManagementProvider -eq 'NuGet' -and $_.Name -ne 'PSGallery' } | + Microsoft.PowerShell.Utility\Select-Object Name, Trusted, SourceLocation ) Microsoft.PowerShell.Utility\Write-Verbose ('Selected {0} NuGet repositories.' -f $repos.Count) @@ -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 2c39f536d..9722e2685 100644 --- a/src/code/ContainerRegistryServerAPICalls.cs +++ b/src/code/ContainerRegistryServerAPICalls.cs @@ -83,7 +83,7 @@ public ContainerRegistryServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmd public override FindResults FindAll(bool includePrerelease, ResourceType type, out ErrorRecord errRecord) { _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindAll()"); - var findResult = FindPackages("*", includePrerelease, out errRecord); + FindResults findResult = FindPackages("*", includePrerelease, out errRecord); if (errRecord != null) { return emptyResponseResults; @@ -168,7 +168,7 @@ public override FindResults FindNameWithTag(string packageName, string[] tags, b public override FindResults FindNameGlobbing(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord) { _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindNameGlobbing()"); - var findResult = FindPackages(packageName, includePrerelease, out errRecord); + FindResults findResult = FindPackages(packageName, includePrerelease, out errRecord); if (errRecord != null) { return emptyResponseResults; @@ -335,7 +335,7 @@ private Stream InstallVersion( } _cmdletPassedIn.WriteVerbose($"Getting manifest for {packageNameLowercase} - {packageVersion}"); - var manifest = GetContainerRegistryRepositoryManifest(packageNameLowercase, packageVersion, containerRegistryAccessToken, out errRecord); + JObject manifest = GetContainerRegistryRepositoryManifest(packageNameLowercase, packageVersion, containerRegistryAccessToken, out errRecord); if (errRecord != null) { return null; @@ -384,7 +384,7 @@ internal string GetContainerRegistryAccessToken(bool needCatalogAccess, out Erro string tenantID = string.Empty; errRecord = null; - var repositoryCredentialInfo = Repository.CredentialInfo; + PSCredentialInfo repositoryCredentialInfo = Repository.CredentialInfo; if (repositoryCredentialInfo != null) { accessToken = Utils.GetContainerRegistryAccessTokenFromSecretManagement( @@ -467,7 +467,7 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistryUrl, bo // check if there is a auth challenge header if (response.Headers.WwwAuthenticate.Count() > 0) { - var authHeader = response.Headers.WwwAuthenticate.First(); + AuthenticationHeaderValue authHeader = response.Headers.WwwAuthenticate.First(); if (authHeader.Scheme == "Bearer") { // check if there is a realm @@ -501,7 +501,7 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistryUrl, bo _cmdletPassedIn.WriteDebug($"Getting anonymous access token from the realm: {url}"); ErrorRecord errRecordTemp = null; - var results = GetHttpResponseJObjectUsingContentHeaders(url, HttpMethod.Get, content, contentHeaders, out errRecordTemp); + JObject results = GetHttpResponseJObjectUsingContentHeaders(url, HttpMethod.Get, content, contentHeaders, out errRecordTemp); if (results == null) { @@ -525,11 +525,11 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistryUrl, bo } catch (HttpRequestException hre) { - errRecord = new ErrorRecord( - hre, - "RegistryAnonymousAcquireError", - ErrorCategory.ConnectionError, - this); + errRecord = new ErrorRecord( + hre, + "RegistryAnonymousAcquireError", + ErrorCategory.ConnectionError, + this); return false; } @@ -556,7 +556,7 @@ internal string GetContainerRegistryRefreshToken(string tenant, string accessTok string content = string.Format(containerRegistryRefreshTokenTemplate, Registry, tenant, accessToken); var contentHeaders = new Collection> { new KeyValuePair("Content-Type", "application/x-www-form-urlencoded") }; string exchangeUrl = string.Format(containerRegistryOAuthExchangeUrlTemplate, Registry); - var results = GetHttpResponseJObjectUsingContentHeaders(exchangeUrl, HttpMethod.Post, content, contentHeaders, out errRecord); + JObject results = GetHttpResponseJObjectUsingContentHeaders(exchangeUrl, HttpMethod.Post, content, contentHeaders, out errRecord); if (errRecord != null || results == null || results["refresh_token"] == null) { return string.Empty; @@ -574,7 +574,7 @@ internal string GetContainerRegistryAccessTokenByRefreshToken(string refreshToke string content = string.Format(containerRegistryAccessTokenTemplate, Registry, refreshToken); var contentHeaders = new Collection> { new KeyValuePair("Content-Type", "application/x-www-form-urlencoded") }; string tokenUrl = string.Format(containerRegistryOAuthTokenUrlTemplate, Registry); - var results = GetHttpResponseJObjectUsingContentHeaders(tokenUrl, HttpMethod.Post, content, contentHeaders, out errRecord); + JObject results = GetHttpResponseJObjectUsingContentHeaders(tokenUrl, HttpMethod.Post, content, contentHeaders, out errRecord); if (errRecord != null || results == null || results["access_token"] == null) { return string.Empty; @@ -639,7 +639,7 @@ internal JObject GetContainerRegistryRepositoryManifest(string packageName, stri _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryRepositoryManifest()"); // example of manifestUrl: https://psgetregistry.azurecr.io/hello-world:3.0.0 string manifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return GetHttpResponseJObjectUsingDefaultHeaders(manifestUrl, HttpMethod.Get, defaultHeaders, out errRecord); } @@ -651,7 +651,7 @@ internal async Task GetContainerRegistryBlobAsync(string packageNam { _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryBlobAsync()"); string blobUrl = string.Format(containerRegistryBlobDownloadUrlTemplate, Registry, packageName, digest); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return await GetHttpContentResponseJObject(blobUrl, defaultHeaders); } @@ -674,7 +674,7 @@ internal JObject FindContainerRegistryImageTags(string packageName, string versi _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindContainerRegistryImageTags()"); string resolvedVersion = string.Equals(version, "*", StringComparison.OrdinalIgnoreCase) ? null : $"/{version}"; string findImageUrl = string.Format(containerRegistryFindImageVersionUrlTemplate, Registry, packageName); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return GetHttpResponseJObjectUsingDefaultHeaders(findImageUrl, HttpMethod.Get, defaultHeaders, out errRecord); } @@ -820,7 +820,7 @@ internal JObject FindContainerRegistryManifest(string packageName, string versio var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version); _cmdletPassedIn.WriteDebug($"GET manifest url: {createManifestUrl}"); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return GetHttpResponseJObjectUsingDefaultHeaders(createManifestUrl, HttpMethod.Get, defaultHeaders, out errRecord); } @@ -913,7 +913,7 @@ internal async Task UploadManifest(string packageName, stri try { var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, packageVersion); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return await PutRequestAsync(createManifestUrl, configPath, isManifest, defaultHeaders); } catch (HttpRequestException e) @@ -1018,7 +1018,7 @@ internal JObject GetHttpResponseJObjectUsingContentHeaders(string url, HttpMetho request.Content.Headers.Clear(); if (contentHeaders != null) { - foreach (var header in contentHeaders) + foreach (KeyValuePair header in contentHeaders) { request.Content.Headers.Add(header.Key, header.Value); } @@ -1088,7 +1088,7 @@ private void SetDefaultHeaders(Collection> defaultH _sessionClient.DefaultRequestHeaders.Clear(); if (defaultHeaders != null) { - foreach (var header in defaultHeaders) + foreach (KeyValuePair header in defaultHeaders) { if (string.Equals(header.Key, "Authorization", StringComparison.OrdinalIgnoreCase)) { @@ -1309,7 +1309,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(); @@ -1400,7 +1400,7 @@ private string UploadNupkgFile(string packageNameLowercase, string containerRegi _cmdletPassedIn.WriteVerbose("Finish uploading blob"); try { - var responseNupkg = EndUploadBlob(moduleLocation, fullNupkgFile, nupkgDigest, isManifest: false, containerRegistryAccessToken).Result; + HttpResponseMessage responseNupkg = EndUploadBlob(moduleLocation, fullNupkgFile, nupkgDigest, isManifest: false, containerRegistryAccessToken).Result; bool uploadSuccessful = responseNupkg.IsSuccessStatusCode; if (!uploadSuccessful) @@ -1453,7 +1453,7 @@ private void CreateAndUploadEmptyFile(string outputNupkgDir, string pkgNameLower } _cmdletPassedIn.WriteVerbose("Finish uploading empty file"); - var emptyResponse = EndUploadBlob(emptyLocation, emptyFilePath, emptyFileDigest, false, containerRegistryAccessToken).Result; + HttpResponseMessage emptyResponse = EndUploadBlob(emptyLocation, emptyFilePath, emptyFileDigest, false, containerRegistryAccessToken).Result; bool uploadSuccessful = emptyResponse.IsSuccessStatusCode; if (!uploadSuccessful) @@ -1737,7 +1737,7 @@ internal async Task GetStartUploadBlobLocation(string packageName, strin _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetStartUploadBlobLocation()"); try { - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); var startUploadUrl = string.Format(containerRegistryStartUploadTemplate, Registry, packageName); return (await GetHttpResponseHeader(startUploadUrl, HttpMethod.Post, defaultHeaders)).Location.ToString(); } @@ -1756,7 +1756,7 @@ internal async Task EndUploadBlob(string location, string f try { var endUploadUrl = string.Format(containerRegistryEndUploadTemplate, Registry, location, digest); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); + Collection> defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); return await PutRequestAsync(endUploadUrl, filePath, isManifest, defaultHeaders); } catch (Exception e) @@ -1787,7 +1787,7 @@ private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionTyp return emptyHashResponses; } - var foundTags = FindContainerRegistryImageTags(packageNameForFind, "*", containerRegistryAccessToken, out errRecord); + JObject foundTags = FindContainerRegistryImageTags(packageNameForFind, "*", containerRegistryAccessToken, out errRecord); if (errRecord != null || foundTags == null) { return emptyHashResponses; @@ -1803,9 +1803,9 @@ private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionTyp return emptyHashResponses; } - var pkgsInDescendingOrder = sortedQualifyingPkgs.Reverse(); + IEnumerable> pkgsInDescendingOrder = sortedQualifyingPkgs.Reverse(); - foreach (var pkgVersionTag in pkgsInDescendingOrder) + foreach (KeyValuePair pkgVersionTag in pkgsInDescendingOrder) { string exactTagVersion = pkgVersionTag.Value.ToString(); Hashtable metadata = GetContainerRegistryMetadata(packageNameForFind, exactTagVersion, containerRegistryAccessToken, out errRecord); @@ -1836,7 +1836,7 @@ private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionTyp SortedDictionary sortedPkgs = new SortedDictionary(VersionComparer.Default); bool isSpecificVersionSearch = versionType == VersionType.SpecificVersion; - foreach (var pkgVersionTagInfo in allPkgVersions) + foreach (JToken pkgVersionTagInfo in allPkgVersions) { string pkgVersionString = pkgVersionTagInfo.ToString(); // determine if the package version that is a repository tag is a valid NuGetVersion @@ -1899,7 +1899,7 @@ private FindResults FindPackages(string packageName, bool includePrerelease, out return emptyResponseResults; } - var pkgResult = FindAllRepositories(containerRegistryAccessToken, out errRecord); + JObject pkgResult = FindAllRepositories(containerRegistryAccessToken, out errRecord); if (errRecord != null) { return emptyResponseResults; @@ -1909,7 +1909,7 @@ private FindResults FindPackages(string packageName, bool includePrerelease, out var isMAR = Repository.IsMARRepository(); // Convert the list of repositories to a list of hashtables - foreach (var repository in pkgResult["repositories"].ToList()) + foreach (JToken repository in pkgResult["repositories"].ToList()) { string repositoryName = repository.ToString(); diff --git a/src/code/FindHelper.cs b/src/code/FindHelper.cs index d8287c689..7cb243f25 100644 --- a/src/code/FindHelper.cs +++ b/src/code/FindHelper.cs @@ -1104,7 +1104,7 @@ internal IEnumerable FindDependencyPackages( { if (currentPkg.Dependencies.Length > 0) { - foreach (var dep in currentPkg.Dependencies) + foreach (Dependency dep in currentPkg.Dependencies) { PSResourceInfo depPkg = null; diff --git a/src/code/FindPSResource.cs b/src/code/FindPSResource.cs index 2709073e7..74176dc26 100644 --- a/src/code/FindPSResource.cs +++ b/src/code/FindPSResource.cs @@ -117,7 +117,7 @@ protected override void BeginProcessing() { _cancellationTokenSource = new CancellationTokenSource(); - var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; + NetworkCredential networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; _findHelper = new FindHelper( cancellationToken: _cancellationTokenSource.Token, 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 1fa98887e..8d33753e2 100644 --- a/src/code/GetHelper.cs +++ b/src/code/GetHelper.cs @@ -44,7 +44,7 @@ public IEnumerable GetInstalledPackages( List pathsToSearch) { _cmdletPassedIn.WriteDebug("In GetHelper::GetInstalledPackages()"); - foreach (var pkg in pkgs) + foreach (PSResourceInfo pkg in pkgs) { // Parse Normalized version if present, if not use Version property of the package NuGetVersion nugetVersion = null; @@ -69,7 +69,7 @@ public IEnumerable GetInstalledPackages( includeMaxVersion: true); // Search by package name. - var foundPkgPaths = FilterPkgPathsByName( + List foundPkgPaths = FilterPkgPathsByName( names: new string[] { pkg.Name }, pathsToSearch); @@ -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 90cc9f20d..e6b5bd937 100644 --- a/src/code/GetInstalledPSResource.cs +++ b/src/code/GetInstalledPSResource.cs @@ -84,7 +84,7 @@ protected override void BeginProcessing() if (Path != null) { WriteDebug($"Provided path is: '{Path}'"); - var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); + System.Collections.ObjectModel.Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); if (resolvedPaths.Count != 1) { ThrowTerminatingError(new ErrorRecord( @@ -121,7 +121,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( diff --git a/src/code/GetPSScriptFileInfo.cs b/src/code/GetPSScriptFileInfo.cs index 2fa1c71e5..1892310c2 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( @@ -38,7 +38,7 @@ protected override void EndProcessing() this)); } - var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); + System.Collections.ObjectModel.Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); if (resolvedPaths.Count != 1) { 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..6f841ca69 100644 --- a/src/code/GroupPolicyRepositoryEnforcement.cs +++ b/src/code/GroupPolicyRepositoryEnforcement.cs @@ -42,7 +42,7 @@ public static bool IsGroupPolicyEnabled() return InternalHooks.GPEnabledStatus; } - var values = ReadGPFromRegistry(); + List>? values = ReadGPFromRegistry(); if (values is not null && values.Count > 0) { @@ -78,11 +78,11 @@ public static bool IsGroupPolicyEnabled() { List allowedUris = new List(); - var allowedRepositories = ReadGPFromRegistry(); + List>? allowedRepositories = ReadGPFromRegistry(); if (allowedRepositories is not null && allowedRepositories.Count > 0) { - foreach (var allowedRepository in allowedRepositories) + foreach (KeyValuePair allowedRepository in allowedRepositories) { allowedUris.Add(allowedRepository.Value); } @@ -96,9 +96,9 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) { bool isAllowed = false; - if(GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) + if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) { - var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); + Uri[]? allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); if (allowedList != null && allowedList.Length > 0) { @@ -117,7 +117,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) { List> allowedRepositories = new List>(); - using (var key = Registry.CurrentUser.OpenSubKey(gpRootPath)) + using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(gpRootPath)) { if (key is null) { @@ -138,7 +138,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) continue; } - using (var psrgKey = key.OpenSubKey(subKey + "\\" + psresourcegetGPPath)) + using (RegistryKey? psrgKey = key.OpenSubKey(subKey + "\\" + psresourcegetGPPath)) { if (psrgKey is null) { @@ -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)) @@ -170,7 +170,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) } string valueString = value.ToString(); - var kvRegValue = ConvertRegValue(valueString); + KeyValuePair kvRegValue = ConvertRegValue(valueString); allowedRepositories.Add(kvRegValue); } } @@ -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/InstallHelper.cs b/src/code/InstallHelper.cs index 83900e413..1c8bf78ee 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -257,7 +257,7 @@ private List ProcessRepositories( return allPkgsInstalled; } - var listOfRepositories = RepositorySettings.Read(repository, out string[] _); + List listOfRepositories = RepositorySettings.Read(repository, out string[] _); var yesToAll = false; var noToAll = false; @@ -866,12 +866,12 @@ private string CreateInstallationTempPath() try { - var dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly - // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator - // with a mask (bitwise complement of desired attributes combination). - // TODO: check the attributes and if it's read only then set it - // attribute may be inherited from the parent - // TODO: are there Linux accommodations we need to consider here? + DirectoryInfo dir = Directory.CreateDirectory(tempInstallPath); // should check it gets created properly + // To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator + // with a mask (bitwise complement of desired attributes combination). + // TODO: check the attributes and if it's read only then set it + // attribute may be inherited from the parent + // TODO: are there Linux accommodations we need to consider here? dir.Attributes &= ~FileAttributes.ReadOnly; } catch (Exception e) @@ -926,7 +926,7 @@ private bool TryInstallToTempPath( try { var pathToFile = Path.Combine(tempInstallPath, $"{pkgName}.{normalizedPkgVersion}.zip"); - using var fs = File.Create(pathToFile); + using FileStream fs = File.Create(pathToFile); responseStream.Seek(0, System.IO.SeekOrigin.Begin); responseStream.CopyTo(fs); fs.Close(); @@ -1105,7 +1105,7 @@ private bool TrySaveNupkgToTempPath( try { var pathToFile = Path.Combine(tempInstallPath, $"{pkgName}.{normalizedPkgVersion}.zip"); - using var fs = File.Create(pathToFile); + using FileStream fs = File.Create(pathToFile); responseStream.Seek(0, System.IO.SeekOrigin.Begin); responseStream.CopyTo(fs); fs.Close(); @@ -1419,7 +1419,7 @@ private bool DetectClobber(string pkgName, Hashtable parsedMetadataHashtable, ou } } - foreach (var pkg in pkgsAlreadyInstalled) + foreach (PSResourceInfo pkg in pkgsAlreadyInstalled) { List duplicateCmdlets = new(); List duplicateCmds = new(); diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index 83943eef9..ad7a00d25 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -270,7 +270,7 @@ protected override void BeginProcessing() // Only need to find packages installed if -Reinstall is not passed in _packagesOnMachine = Reinstall ? new HashSet(StringComparer.CurrentCultureIgnoreCase) : Utils.GetInstalledPackages(pathsToSearch, this); - var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; + NetworkCredential networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; _installHelper = new InstallHelper(cmdletPassedIn: this, networkCredential: networkCred); } 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/InternalHooks.cs b/src/code/InternalHooks.cs index 99d6104ce..f8fcee64d 100644 --- a/src/code/InternalHooks.cs +++ b/src/code/InternalHooks.cs @@ -19,7 +19,7 @@ public class InternalHooks public static void SetTestHook(string property, object value) { - var fieldInfo = typeof(InternalHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); + FieldInfo fieldInfo = typeof(InternalHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); fieldInfo?.SetValue(null, value); } diff --git a/src/code/LocalServerApiCalls.cs b/src/code/LocalServerApiCalls.cs index cc43c340d..385df99cc 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; @@ -173,7 +173,7 @@ public override FindResults FindVersionGlobbing(string packageName, VersionRange // Versions are present in pkgVersionsList in asc order, whereas 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) @@ -318,7 +318,7 @@ private FindResults FindNameHelper(string packageName, string[] tags, bool inclu 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; @@ -436,7 +436,7 @@ private FindResults FindVersionHelper(string packageName, string version, string 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; @@ -645,7 +645,7 @@ private Hashtable GetMetadataFromNupkg(string packageName, string packagePath, s try { - var dir = Directory.CreateDirectory(tempDiscoveryPath); + DirectoryInfo dir = Directory.CreateDirectory(tempDiscoveryPath); dir.Attributes &= ~FileAttributes.ReadOnly; // copy .nupkg @@ -724,7 +724,7 @@ 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 @@ -892,9 +892,9 @@ 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); @@ -920,7 +920,8 @@ 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( @@ -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..57ac3d735 100644 --- a/src/code/ModuleInitAndCleanup.cs +++ b/src/code/ModuleInitAndCleanup.cs @@ -97,14 +97,14 @@ internal class AssemblyLoadContextProxy private AssemblyLoadContextProxy(Type alc, string loadContextName) { - var ctor = alc.GetConstructor(new[] { typeof(string), typeof(bool) }); + ConstructorInfo ctor = alc.GetConstructor(new[] { typeof(string), typeof(bool) }); _loadFromAssemblyPath = alc.GetMethod("LoadFromAssemblyPath", new[] { typeof(string) }); _customContext = ctor.Invoke(new object[] { loadContextName, false }); } 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) @@ -114,7 +114,7 @@ internal static AssemblyLoadContextProxy CreateLoadContext(string name) throw new ArgumentNullException(nameof(name)); } - var alc = typeof(object).Assembly.GetType("System.Runtime.Loader.AssemblyLoadContext"); + Type alc = typeof(object).Assembly.GetType("System.Runtime.Loader.AssemblyLoadContext"); return alc is not null ? new AssemblyLoadContextProxy(alc, name) diff --git a/src/code/NuGetServerAPICalls.cs b/src/code/NuGetServerAPICalls.cs index 1497c83da..adc0ec582 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; @@ -171,7 +171,7 @@ public override FindResults FindName(string packageName, bool includePrerelease, var queryBuilder = new NuGetV2QueryBuilder(new Dictionary{ { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion"); @@ -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); } /// @@ -376,7 +376,7 @@ public override FindResults FindVersion(string packageName, string version, Reso var queryBuilder = new NuGetV2QueryBuilder(new Dictionary{ { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; // We need to explicitly add 'Id eq ' whenever $filter is used, otherwise arbitrary results are returned. filterBuilder.AddCriterion($"Id eq '{packageName}'"); @@ -401,7 +401,7 @@ public override FindResults FindVersionWithTag(string packageName, string versio var queryBuilder = new NuGetV2QueryBuilder(new Dictionary{ { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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) @@ -562,12 +562,15 @@ private string FindAllFromEndPoint(bool includePrerelease, int skip, out ErrorRe { "$orderBy", "Id desc" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } @@ -590,12 +593,15 @@ private string FindTagFromEndpoint(string[] tags, bool includePrerelease, int sk { "$orderBy", "Id desc" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; - if (includePrerelease) { + if (includePrerelease) + { queryBuilder.AdditionalParameters["includePrerelease"] = "true"; filterBuilder.AddCriterion("IsAbsoluteLatestVersion"); - } else { + } + else + { filterBuilder.AddCriterion("IsLatestVersion"); } @@ -625,17 +631,20 @@ private string FindNameGlobbing(string packageName, bool includePrerelease, int { "$orderBy", "NormalizedVersion desc" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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) { @@ -705,16 +714,19 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, bool i { "$orderBy", "Id desc" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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) { @@ -795,7 +807,7 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange { "$orderBy", "NormalizedVersion desc" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; //and IsPrerelease eq false // ex: @@ -840,7 +852,8 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange filterBuilder.AddCriterion(maxPart); } - if (!includePrerelease) { + if (!includePrerelease) + { filterBuilder.AddCriterion("IsPrerelease eq false"); } @@ -863,7 +876,7 @@ private Stream InstallName(string packageName, out ErrorRecord errRecord) { _cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::InstallName()"); var requestUrl = $"{Repository.Uri}/Packages/(Id='{packageName}')/Download"; - var response = HttpRequestCallForContent(requestUrl, out errRecord); + HttpContent response = HttpRequestCallForContent(requestUrl, out errRecord); if (response is null) { @@ -891,7 +904,7 @@ private Stream InstallVersion(string packageName, string version, out ErrorRecor { _cmdletPassedIn.WriteDebug("In NuGetServerAPICalls::InstallVersion()"); var requestUrl = $"{Repository.Uri}/Packages(Id='{packageName}',Version='{version}')/Download"; - var response = HttpRequestCallForContent(requestUrl, out errRecord); + HttpContent response = HttpRequestCallForContent(requestUrl, out errRecord); if (response is null) { diff --git a/src/code/NuGetServerResponseUtil.cs b/src/code/NuGetServerResponseUtil.cs index 19b7499d4..02919ea91 100644 --- a/src/code/NuGetServerResponseUtil.cs +++ b/src/code/NuGetServerResponseUtil.cs @@ -38,7 +38,7 @@ public override IEnumerable ConvertToPSResourceResult(FindResu foreach (string response in responses) { - var elemList = ConvertResponseToXML(response); + XmlNode[] elemList = ConvertResponseToXML(response); if (elemList.Length == 0) { // this indicates we got a non-empty, XML response (as noticed for V2 server) but it's not a response that's meaningful (contains 'properties') @@ -47,7 +47,7 @@ public override IEnumerable ConvertToPSResourceResult(FindResu yield return new PSResourceResult(returnedObject: null, exception: notFoundException, isTerminatingError: false); } - foreach (var element in elemList) + foreach (XmlNode element in elemList) { if (!PSResourceInfo.TryConvertFromXml(element, out PSResourceInfo psGetInfo, Repository, out string errorMsg)) { @@ -69,7 +69,8 @@ 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(); 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/PSResourceInfo.cs b/src/code/PSResourceInfo.cs index d2351da35..b0fd43984 100644 --- a/src/code/PSResourceInfo.cs +++ b/src/code/PSResourceInfo.cs @@ -368,7 +368,7 @@ public static bool TryRead( System.IO.File.ReadAllText( filePath)); - var additionalMetadata = GetProperty>(nameof(PSResourceInfo.AdditionalMetadata), psObjectInfo); + Dictionary additionalMetadata = GetProperty>(nameof(PSResourceInfo.AdditionalMetadata), psObjectInfo); Version version = GetVersionInfo(psObjectInfo, additionalMetadata, out string prerelease); psGetInfo = new PSResourceInfo( @@ -492,7 +492,7 @@ public static bool TryConvertFromXml( { Hashtable metadata = new Hashtable(StringComparer.InvariantCultureIgnoreCase); - var entryChildNodes = entry.ChildNodes; + XmlNodeList entryChildNodes = entry.ChildNodes; foreach (XmlElement entryChild in entryChildNodes) { var entryKey = entryChild.LocalName; @@ -507,7 +507,7 @@ public static bool TryConvertFromXml( } else if (entryKey.Equals("properties")) { - var propertyChildNodes = entryChild.ChildNodes; + XmlNodeList propertyChildNodes = entryChild.ChildNodes; foreach (XmlElement propertyChild in propertyChildNodes) { var propertyKey = propertyChild.LocalName; @@ -568,7 +568,7 @@ public static bool TryConvertFromXml( } } - var typeInfo = ParseHttpMetadataType(metadata["Tags"] as string[], out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); + ResourceType typeInfo = ParseHttpMetadataType(metadata["Tags"] as string[], out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); var resourceHashtable = new Hashtable { { nameof(PSResourceInfo.Includes.Command), new PSObject(commandNames) }, { nameof(PSResourceInfo.Includes.Cmdlet), new PSObject(cmdletNames) }, @@ -695,7 +695,7 @@ public static bool TryConvertFromJson( { var arrayLength = tagsElement.GetArrayLength(); List tags = new List(arrayLength); - foreach (var tag in tagsElement.EnumerateArray()) + foreach (JsonElement tag in tagsElement.EnumerateArray()) { tags.Add(tag.ToString()); } @@ -947,7 +947,7 @@ public static bool TryConvertFromContainerRegistryJson( { var arrayLength = tagsElement.GetArrayLength(); List tags = new List(arrayLength); - foreach (var tag in tagsElement.EnumerateArray()) + foreach (JsonElement tag in tagsElement.EnumerateArray()) { tags.Add(tag.ToString()); } @@ -1060,7 +1060,7 @@ public static bool TryConvertFromContainerRegistryJson( { var arrayLength = psDataTagsElement.GetArrayLength(); List tags = new List(arrayLength); - foreach (var tag in psDataTagsElement.EnumerateArray()) + foreach (JsonElement tag in psDataTagsElement.EnumerateArray()) { tags.Add(tag.ToString()); } @@ -1167,7 +1167,7 @@ public static bool TryConvertFromHashtableForPsd1( Hashtable[] requiredModulesHashArray = requiredModulesHashList.ToArray(); Dependency[] deps = GetDependenciesForPsd1(requiredModulesHashArray); - var typeInfo = ParseHttpMetadataTypeForLocalRepo(pkgMetadata, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); + ResourceType typeInfo = ParseHttpMetadataTypeForLocalRepo(pkgMetadata, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); var resourceHashtable = new Hashtable { { nameof(PSResourceInfo.Includes.Command), new PSObject(commandNames) }, { nameof(PSResourceInfo.Includes.Cmdlet), new PSObject(cmdletNames) }, @@ -1241,7 +1241,7 @@ public static bool TryConvertFromHashtableForPs1( try { string[] tagsEntry = pkgMetadata["Tags"] as string[]; - var typeInfo = ParseHttpMetadataTypeForLocalRepo(pkgMetadata, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); + ResourceType typeInfo = ParseHttpMetadataTypeForLocalRepo(pkgMetadata, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); var resourceHashtable = new Hashtable { { nameof(PSResourceInfo.Includes.Command), new PSObject(commandNames) }, { nameof(PSResourceInfo.Includes.Cmdlet), new PSObject(cmdletNames) }, @@ -1313,7 +1313,7 @@ public static bool TryConvertFromHashtableForNuspec( { string tagsEntry = pkgMetadata["tags"] as string; string[] tags = tagsEntry.Split(new char[] { ' ' }); - var typeInfo = ParseHttpMetadataType(tags, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); + ResourceType typeInfo = ParseHttpMetadataType(tags, out ArrayList commandNames, out ArrayList cmdletNames, out ArrayList dscResourceNames); var resourceHashtable = new Hashtable { { nameof(PSResourceInfo.Includes.Command), new PSObject(commandNames) }, { nameof(PSResourceInfo.Includes.Cmdlet), new PSObject(cmdletNames) }, @@ -1387,7 +1387,7 @@ private static T ConvertToType(PSObject psObject) } var dict = new Dictionary(); - foreach (var prop in psObject.Properties) + foreach (PSPropertyInfo prop in psObject.Properties) { dict.Add(prop.Name, prop.Value.ToString()); } @@ -1845,7 +1845,7 @@ private PSObject ConvertToCustomObject() AdditionalMetadata[nameof(NormalizedVersion)] = NormalizedVersion; } - foreach (var item in AdditionalMetadata) + foreach (KeyValuePair item in AdditionalMetadata) { additionalMetadata.Properties.Add(new PSNoteProperty(item.Key, item.Value)); } 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 cfbe78e75..b367c97a4 100644 --- a/src/code/PSScriptFileInfo.cs +++ b/src/code/PSScriptFileInfo.cs @@ -109,7 +109,7 @@ internal static bool TryParseScriptFileContents( ref string[] remainingFileContent, out ErrorRecord error) { - error= null; + error = null; psScriptInfoCommentContent = new List(); helpInfoCommentContent = new List(); @@ -323,7 +323,7 @@ internal static bool TryTestPSScriptFileInfo( remainingFileContent: ref remainingFileContent, out ErrorRecord parseError)) { - errors = new ErrorRecord[]{parseError}; + errors = new ErrorRecord[] { parseError }; return false; } @@ -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 215cf47ae..50e29475c 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,7 +41,7 @@ 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.ParseContentIntoObj() would then populate those properties. /// - internal PSScriptHelp() {} + internal PSScriptHelp() { } #endregion @@ -65,11 +65,11 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord error) } // 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)) @@ -156,7 +156,7 @@ internal bool ValidateParsedContent(Hashtable parsedHelpMetadata, out ErrorRecor 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)) { diff --git a/src/code/PSScriptMetadata.cs b/src/code/PSScriptMetadata.cs index a9aa9995e..f7f430203 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.ParseContentIntoObj() would then populate those properties. /// - internal PSScriptMetadata() {} + internal PSScriptMetadata() { } #endregion @@ -178,39 +178,39 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error string[] delimiter = 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"); } } 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; @@ -323,7 +323,7 @@ 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"), @@ -332,7 +332,7 @@ internal bool ValidateParsedContent(Hashtable parsedMetadata, out ErrorRecord[] 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"), @@ -341,7 +341,7 @@ internal bool ValidateParsedContent(Hashtable parsedMetadata, out ErrorRecord[] 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"), @@ -506,27 +506,33 @@ 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; } diff --git a/src/code/PSScriptRequires.cs b/src/code/PSScriptRequires.cs index 0681b34ec..8d20a0ca8 100644 --- a/src/code/PSScriptRequires.cs +++ b/src/code/PSScriptRequires.cs @@ -65,7 +65,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.ParseContentIntoObj() would then populate those properties. /// - internal PSScriptRequires() {} + internal PSScriptRequires() { } #endregion @@ -93,7 +93,7 @@ internal bool ParseContentIntoObj(string[] commentLines, out ErrorRecord[] error try { - var ast = Parser.ParseInput( + ScriptBlockAst ast = Parser.ParseInput( requiresComment, out Token[] tokens, out ParseError[] parserErrors); @@ -229,7 +229,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 619c1da56..3f7111d4d 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); @@ -328,7 +328,7 @@ out string[] _ } } - internal void PushResource(string Repository, string modulePrefix, bool SkipDependenciesCheck, NetworkCredential _networkCredential) + internal void PushResource(string Repository, string modulePrefix, bool SkipDependenciesCheck, NetworkCredential networkCredential) { try { @@ -381,7 +381,7 @@ internal void PushResource(string Repository, string modulePrefix, bool SkipDepe } // Set network credentials via passed in credentials, AzArtifacts CredentialProvider, or SecretManagement. - _networkCredential = repository.SetNetworkCredentials(_networkCredential, _cmdletPassedIn); + _networkCredential = repository.SetNetworkCredentials(networkCredential, _cmdletPassedIn); // Check if dependencies already exist within the repo if: // 1) the resource to publish has dependencies and @@ -469,7 +469,7 @@ internal void PushResource(string Repository, string modulePrefix, bool SkipDepe } else { - if(_isNupkgPathSpecified) + if (_isNupkgPathSpecified) { outputNupkgDir = pathToNupkgToPublish; } @@ -669,7 +669,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o // to accommodate for the appropriate publish location. string publishLocation = repoUri.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoUri + "/package" : repoUri; - var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null); + ISettings settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null); var success = false; var sourceProvider = new PackageSourceProvider(settings); @@ -741,7 +741,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")) @@ -840,7 +841,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi return; } - var packageSource = sourceProvider.LoadPackageSources().FirstOrDefault(s => s.Source == source); + PackageSource packageSource = sourceProvider.LoadPackageSources().FirstOrDefault(s => s.Source == source); if (packageSource != null) { if (!packageSource.IsEnabled) @@ -850,7 +851,7 @@ private void InjectCredentialsToSettings(ISettings settings, IPackageSourceProvi } - var networkCred = Credential == null ? _networkCredential : Credential.GetNetworkCredential(); + NetworkCredential networkCred = Credential == null ? _networkCredential : Credential.GetNetworkCredential(); string key; if (packageSource == null) @@ -1280,7 +1281,7 @@ private bool CheckDependenciesExist(Hashtable dependencies, string repositoryNam var repository = new[] { repositoryName }; // Note: we set prerelease argument for FindByResourceName() to true because if no version is specified we want latest version (including prerelease). // If version is specified it will get that one. There is also no way to specify a prerelease flag with RequiredModules hashtable of dependency so always try to get latest version. - var dependencyFound = findHelper.FindByResourceName(new string[] { depName }, ResourceType.Module, versionRange, nugetVersion, versionType, depVersion, prerelease: true, tag: null, repository, includeDependencies: false, suppressErrors: true); + IEnumerable dependencyFound = findHelper.FindByResourceName(new string[] { depName }, ResourceType.Module, versionRange, nugetVersion, versionType, depVersion, prerelease: true, tag: null, repository, includeDependencies: false, suppressErrors: true); if (dependencyFound == null || !dependencyFound.Any()) { _cmdletPassedIn.WriteError(new ErrorRecord( @@ -1395,7 +1396,7 @@ internal Hashtable GetMetadataFromNupkg(string copiedNupkgPath, string packageNa try { - var dir = Directory.CreateDirectory(extractPath); + DirectoryInfo dir = Directory.CreateDirectory(extractPath); dir.Attributes &= ~FileAttributes.ReadOnly; // change extension to .zip diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index e734cf3de..06eaa91fd 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -43,7 +43,7 @@ public sealed class PublishPSResource : PSCmdlet /// 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; } @@ -79,7 +79,8 @@ public sealed class PublishPSResource : PSCmdlet /// [Parameter] [ValidateNotNullOrEmpty] - public Uri Proxy { + public Uri Proxy + { set { if (value != null) @@ -98,7 +99,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 8d86face3..ca15adabc 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -67,7 +67,7 @@ class RegisterPSResourceRepository : PSCmdlet, IDynamicParameters /// [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. @@ -235,7 +235,7 @@ private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repo WriteDebug("In RegisterPSResourceRepository::PSGalleryParameterSetHelper()"); Uri psGalleryUri = new Uri(PSGalleryRepoUri); WriteDebug("Internal name and uri values for PSGallery are hardcoded and validated. Priority and trusted values, if passed in, also validated"); - var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName, + PSRepositoryInfo addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName, psGalleryUri, repoPriority, repoTrusted, @@ -352,7 +352,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)) @@ -394,11 +394,11 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { WriteDebug($"Registering repository '{repo["Name"]}' with uri '{repoUri}'"); - var addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(), + PSRepositoryInfo addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(), repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : DefaultTrusted, - apiVersion: repo.ContainsKey("Trusted") ? (PSRepositoryInfo.APIVersion?) repo["ApiVersion"] : null, + apiVersion: repo.ContainsKey("Trusted") ? (PSRepositoryInfo.APIVersion?)repo["ApiVersion"] : null, repoCredentialInfo, repo.ContainsKey("CredentialProvider") ? (PSRepositoryInfo.CredentialProviderType?)repo["CredentialProvider"] : null, Force, @@ -448,7 +448,8 @@ public class CredentialProviderDynamicParameters /// Specifies which credential provider to use. /// [Parameter] - public PSRepositoryInfo.CredentialProviderType? CredentialProvider { + public PSRepositoryInfo.CredentialProviderType? CredentialProvider + { get { return _credProvider; diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 39f129006..00f512c48 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -148,7 +148,7 @@ public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri return null; } - var repo = Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, resolvedCredentialProvider, resolvedAPIVersion, force); + PSRepositoryInfo repo = Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, resolvedCredentialProvider, resolvedAPIVersion, force); return repo; } @@ -259,7 +259,7 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit // Else, keep going // Get root of XDocument (XElement) - var root = doc.Root; + XElement root = doc.Root; // Create new element XElement newElement = new XElement( @@ -311,7 +311,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, credentialProvider, force:true, cmdletPassedIn, out errorMsg); + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, apiVersion, repoCredentialInfo, credentialProvider, force: true, cmdletPassedIn, out errorMsg); } // Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted. @@ -345,7 +345,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio // Else, keep going // Get root of XDocument (XElement) - var root = doc.Root; + XElement root = doc.Root; // A null Uri (or Url) value passed in signifies the Uri was not attempted to be set. // So only set Uri attribute if non-null value passed in for repoUri @@ -373,14 +373,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)); } @@ -449,7 +449,7 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) { - var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); + Uri[] allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); } @@ -511,7 +511,7 @@ public static List Remove(string[] repoNames, out string[] err } // Get root of XDocument (XElement) - var root = doc.Root; + XElement root = doc.Root; foreach (string repo in repoNames) { @@ -725,7 +725,7 @@ public static List Read(string[] repoNames, out string[] error bool repoMatch = false; WildcardPattern nameWildCardPattern = new WildcardPattern(repo, WildcardOptions.IgnoreCase); - foreach (var node in doc.Descendants("Repository").Where(e => e.Attribute("Name") != null && nameWildCardPattern.IsMatch(e.Attribute("Name").Value))) + foreach (XElement node in doc.Descendants("Repository").Where(e => e.Attribute("Name") != null && nameWildCardPattern.IsMatch(e.Attribute("Name").Value))) { if (node.Attribute("Priority") == null) { @@ -840,7 +840,7 @@ public static List Read(string[] repoNames, out string[] error errorList = tempErrorList.ToArray(); // Sort by priority, then by repo name - var reposToReturn = foundRepos.OrderBy(x => x.Priority).ThenBy(x => x.Name); + IOrderedEnumerable reposToReturn = foundRepos.OrderBy(x => x.Priority).ThenBy(x => x.Name); return reposToReturn.ToList(); } diff --git a/src/code/ResponseUtil.cs b/src/code/ResponseUtil.cs index aac2cdbd1..db6c95b5a 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, bool isResourceRequestedWithWildcard = false); #endregion - + } } diff --git a/src/code/SavePSResource.cs b/src/code/SavePSResource.cs index 26d481fce..d3cf7d1a3 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; } /// @@ -187,7 +187,7 @@ protected override void BeginProcessing() // This is to create a better experience for those who have just installed v3 and want to get up and running quickly RepositorySettings.CheckRepositoryStore(); - var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; + NetworkCredential networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; // If path is not provided, use current path. if (string.IsNullOrEmpty(_path)) @@ -213,7 +213,7 @@ protected override void ProcessRecord() break; case InputObjectParameterSet: - foreach (var inputObj in InputObject) + foreach (PSResourceInfo inputObj in InputObject) { string normalizedVersionString = Utils.GetNormalizedVersionString(inputObj.Version.ToString(), inputObj.Prerelease); ProcessSaveHelper( @@ -288,7 +288,7 @@ private void ProcessSaveHelper(string[] pkgNames, string pkgVersion, bool pkgPre pkgPrerelease = true; } - var installedPkgs = _installHelper.BeginInstallPackages( + IEnumerable installedPkgs = _installHelper.BeginInstallPackages( names: namesToSave, versionRange: versionRange, nugetVersion: nugetVersion, 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 d46c5ba48..4e14a31c3 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -169,7 +169,7 @@ protected override void ProcessRecord() List items = new List(); - switch(ParameterSetName) + switch (ParameterSetName) { case NameParameterSet: try @@ -227,7 +227,7 @@ protected override void ProcessRecord() if (PassThru) { - foreach(PSRepositoryInfo item in items) + foreach (PSRepositoryInfo item in items) { WriteObject(item); } @@ -294,13 +294,13 @@ 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)) @@ -314,7 +314,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { - var updatedRepo = RepositorySettings.UpdateRepositoryStore(repo["Name"].ToString(), + PSRepositoryInfo updatedRepo = RepositorySettings.UpdateRepositoryStore(repo["Name"].ToString(), repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, repoTrusted, diff --git a/src/code/TestPSScriptFile.cs b/src/code/TestPSScriptFile.cs index b6fa575a3..33480e1dd 100644 --- a/src/code/TestPSScriptFile.cs +++ b/src/code/TestPSScriptFile.cs @@ -40,7 +40,7 @@ protected override void EndProcessing() this)); } - var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); + System.Collections.ObjectModel.Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); if (resolvedPaths.Count != 1) { ThrowTerminatingError(new ErrorRecord( diff --git a/src/code/UninstallPSResource.cs b/src/code/UninstallPSResource.cs index 4cd0a4d19..26fc0645f 100644 --- a/src/code/UninstallPSResource.cs +++ b/src/code/UninstallPSResource.cs @@ -108,7 +108,7 @@ protected override void ProcessRecord() 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) { @@ -128,7 +128,7 @@ protected override void ProcessRecord() if (!UninstallPkgHelper(out List errRecords)) { - foreach (var err in errRecords) + foreach (ErrorRecord err in errRecords) { WriteError(err); } @@ -136,7 +136,8 @@ protected override void ProcessRecord() break; case InputObjectParameterSet: - foreach (var inputObj in InputObject) { + foreach (PSResourceInfo 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( @@ -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 version '{Version}' of resource '{String.Join(", ", Name)}' because it does not exist"; @@ -401,7 +403,7 @@ private bool CheckIfDependency(string pkgName, string version, out ErrorRecord e { for (int i = 0; i < _dependentModules.Count; i++) { - var reqModule = _dependentModules[i].RequiredModules; + ReadOnlyCollection reqModule = _dependentModules[i].RequiredModules; for (int j = 0; j < reqModule.Count; j++) { @@ -452,7 +454,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 2644128d7..7cc75a114 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 aa8d38e88..e59290d80 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)) @@ -641,10 +641,10 @@ private void CreateModuleManifestHelper(Hashtable parsedMetadata, string resolve { try { - var results = pwsh.AddCommand("Microsoft.PowerShell.Core\\New-ModuleManifest").AddParameters(parsedMetadata).Invoke(); + System.Collections.ObjectModel.Collection results = pwsh.AddCommand("Microsoft.PowerShell.Core\\New-ModuleManifest").AddParameters(parsedMetadata).Invoke(); if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { WriteError(err); } @@ -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)) { @@ -990,10 +991,10 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string { try { - var results = pwsh.AddCommand("Microsoft.PowerShell.Core\\New-ModuleManifest").AddParameters(parsedMetadata).Invoke(); + System.Collections.ObjectModel.Collection results = pwsh.AddCommand("Microsoft.PowerShell.Core\\New-ModuleManifest").AddParameters(parsedMetadata).Invoke(); if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { WriteError(err); } @@ -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..aea61f49b 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(); } @@ -158,14 +158,14 @@ protected override void BeginProcessing() _pathsToInstallPkg = Utils.GetAllInstallationPaths(this, Scope); _cancellationTokenSource = new CancellationTokenSource(); - var networkCred = Credential != null ? new NetworkCredential(Credential.UserName, Credential.Password) : null; + NetworkCredential 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; } @@ -194,7 +194,7 @@ protected override void ProcessRecord() return; } - var installedPkgs = _installHelper.BeginInstallPackages( + IEnumerable installedPkgs = _installHelper.BeginInstallPackages( names: namesToUpdate, versionRange: versionRange, nugetVersion: nugetVersion, @@ -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)) @@ -292,7 +292,7 @@ private string[] ProcessPackageNames( var installedPackages = new Dictionary(StringComparer.InvariantCultureIgnoreCase); // selectPrereleaseOnly is false because even if Prerelease is true we want to include both stable and prerelease, not select prerelease only. - foreach (var installedPackage in getHelper.GetPackagesFromPath( + foreach (PSResourceInfo installedPackage in getHelper.GetPackagesFromPath( name: namesToProcess, versionRange: VersionRange.All, pathsToSearch: Utils.GetAllResourcePaths(this, Scope), @@ -311,7 +311,7 @@ private string[] ProcessPackageNames( "NoInstalledPackagesFoundWithNameProvided", ErrorCategory.InvalidOperation, this)); - + return Utils.EmptyStrArray; } @@ -332,7 +332,7 @@ private string[] ProcessPackageNames( // Find all packages selected for updating in provided repositories. var repositoryPackages = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - foreach (var foundResource in _findHelper.FindByResourceName( + foreach (PSResourceInfo foundResource in _findHelper.FindByResourceName( name: installedPackages.Keys.ToArray(), type: ResourceType.None, versionRange: versionRange, @@ -395,7 +395,7 @@ private string[] ProcessPackageNames( // cases in which to update: // versionRange: null/*, , repoVersion : 2.0.0-beta, installedVersion: 1.5.0 - // versionRange: [1.8.0, 2.1.0] , repoVersion: 2.0.0, installedVersion: 1.6.0 + // versionRange: [1.8.0, 2.1.0] , repoVersion: 2.0.0, installedVersion: 1.6.0 // versionRange: [, 2.1.0] , repoVersion: 2.0.0, installedVersion: 1.5.0 (installedVersion satisfies requirement, but there's later version) if (((versionRange == null || versionRange == VersionRange.All) && repoVersion > installedVersion) || versionRange != null && repoVersion > installedVersion && versionRange.Satisfies(repoVersion)) diff --git a/src/code/UpdatePSScriptFileInfo.cs b/src/code/UpdatePSScriptFileInfo.cs index c34e11238..94f83445e 100644 --- a/src/code/UpdatePSScriptFileInfo.cs +++ b/src/code/UpdatePSScriptFileInfo.cs @@ -187,7 +187,7 @@ protected override void EndProcessing() this)); } - var resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); + System.Collections.ObjectModel.Collection resolvedPaths = GetResolvedProviderPathFromPSPath(Path, out ProviderInfo provider); if (resolvedPaths.Count != 1) { ThrowTerminatingError(new ErrorRecord( @@ -299,7 +299,7 @@ protected override void EndProcessing() 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 61b9e6b04..209b13690 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -141,7 +141,8 @@ public static string[] GetStringArrayFromString(string[] delimiter, 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("*")) { @@ -551,7 +553,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( { using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { - var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( + Collection module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( new Hashtable() { { "Name", "Microsoft.PowerShell.SecretManagement"}, { "PassThru", true} @@ -559,7 +561,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -581,7 +583,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( } pwsh.Commands.Clear(); - var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Get-Secret").AddParameters( + Collection results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Get-Secret").AddParameters( new Hashtable() { { "Vault", repositoryCredentialInfo.VaultName }, { "Name", repositoryCredentialInfo.SecretName } @@ -589,7 +591,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -656,7 +658,6 @@ public static string GetAzAccessToken(PSCmdlet cmdletPassedIn) ExcludeVisualStudioCredential = true, ExcludeWorkloadIdentityCredential = true, ExcludeManagedIdentityCredential = true, // ManagedIdentityCredential makes the experience slow - ExcludeSharedTokenCacheCredential = true, // SharedTokenCacheCredential is not supported on macOS ExcludeAzureCliCredential = false, ExcludeAzurePowerShellCredential = false, ExcludeInteractiveBrowserCredential = false @@ -669,7 +670,7 @@ public static string GetAzAccessToken(PSCmdlet cmdletPassedIn) { using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { - var token = dCred.GetTokenAsync(tokenRequestContext, cts.Token).GetAwaiter().GetResult(); + AccessToken token = dCred.GetTokenAsync(tokenRequestContext, cts.Token).GetAwaiter().GetResult(); return token.Token; } } @@ -701,7 +702,7 @@ public static string GetContainerRegistryAccessTokenFromSecretManagement( return null; } - var results = PowerShellInvoker.InvokeScriptWithHost( + Collection results = PowerShellInvoker.InvokeScriptWithHost( cmdlet: cmdletPassedIn, script: @" param ( @@ -771,7 +772,7 @@ public static void SaveRepositoryCredentialToSecretManagementVault( { using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { - var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( + Collection module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( new Hashtable() { { "Name", "Microsoft.PowerShell.SecretManagement"}, { "PassThru", true} @@ -779,7 +780,7 @@ public static void SaveRepositoryCredentialToSecretManagementVault( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -801,7 +802,7 @@ public static void SaveRepositoryCredentialToSecretManagementVault( } pwsh.Commands.Clear(); - var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Set-Secret").AddParameters( + Collection results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Set-Secret").AddParameters( new Hashtable() { { "Secret", repositoryCredentialInfo.Credential}, { "Vault", repositoryCredentialInfo.VaultName }, @@ -810,7 +811,7 @@ public static void SaveRepositoryCredentialToSecretManagementVault( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -840,7 +841,7 @@ public static bool IsSecretManagementModuleAvailable( { using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { - var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( + Collection module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( new Hashtable() { { "Name", "Microsoft.PowerShell.SecretManagement"}, { "PassThru", true}, @@ -849,7 +850,7 @@ public static bool IsSecretManagementModuleAvailable( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -887,7 +888,7 @@ public static bool IsSecretManagementVaultAccessible( { using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { - var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( + Collection module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters( new Hashtable() { { "Name", "Microsoft.PowerShell.SecretManagement"}, { "PassThru", true} @@ -895,7 +896,7 @@ public static bool IsSecretManagementVaultAccessible( if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -909,14 +910,14 @@ public static bool IsSecretManagementVaultAccessible( } pwsh.Commands.Clear(); - var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Test-SecretVault").AddParameters( + Collection results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Test-SecretVault").AddParameters( new Hashtable() { { "Name", repositoryCredentialInfo.VaultName } }).Invoke(); if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0) { - foreach (var err in pwsh.Streams.Error) + foreach (ErrorRecord err in pwsh.Streams.Error) { cmdletPassedIn.WriteError(err); } @@ -1590,7 +1591,8 @@ public static bool TryCreateModuleSpecification( public static SecureString ConvertToSecureString(string input) { - if (input == null) { + if (input == null) + { throw new ArgumentNullException(nameof(input)); } @@ -1672,7 +1674,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)) { @@ -1686,7 +1688,7 @@ public static void DeleteDirectory(string dirPath) { try { - Directory.Delete(dirPath,true); + Directory.Delete(dirPath, true); return; } catch (Exception ex) @@ -1933,11 +1935,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( // We are running trusted script. iss.LanguageMode = PSLanguageMode.FullLanguage; // Import the current PowerShellGet module. - var modPathObjects = cmdlet.InvokeCommand.InvokeScript( + Collection modPathObjects = cmdlet.InvokeCommand.InvokeScript( script: "(Microsoft.PowerShell.Core\\Get-Module -Name Microsoft.PowerShell.PSResourceGet).Path"); string modPath = (modPathObjects.Count > 0 && modPathObjects[0].BaseObject is string modPathStr) @@ -2087,12 +2090,13 @@ public static Collection InvokeScriptWithHost( try { // Invoke the script. - var results = ps.Invoke(); + Collection results = ps.Invoke(); // Extract expected output types from results pipeline. - foreach (var psItem in results) + foreach (PSObject psItem in results) { - if (psItem == null || psItem.BaseObject == null) { continue; } + if (psItem == null || psItem.BaseObject == null) + { continue; } switch (psItem.BaseObject) { @@ -2121,7 +2125,7 @@ public static Collection InvokeScriptWithHost( break; case T[] resultArray: - foreach (var item in resultArray) + foreach (T item in resultArray) { returnCollection.Add(item); } @@ -2191,7 +2195,7 @@ internal static bool CheckAuthenticodeSignature( } // If any file authenticode signatures are not valid, return false. - foreach (var signatureObject in authenticodeSignatures) + foreach (PSObject signatureObject in authenticodeSignatures) { Signature signature = (Signature)signatureObject.BaseObject; if (!signature.Status.Equals(SignatureStatus.Valid)) diff --git a/src/code/V2QueryBuilder.cs b/src/code/V2QueryBuilder.cs index c4891d5dd..05c605247 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. /// @@ -72,7 +72,7 @@ internal NuGetV2QueryBuilder(Dictionary parameters) : this() internal string BuildQueryString() { - var QueryParameters = HttpUtility.ParseQueryString(""); + NameValueCollection QueryParameters = HttpUtility.ParseQueryString(""); if (FilterBuilder.CriteriaCount > 0 || ShouldEmitEmptyFilter) @@ -80,11 +80,12 @@ internal string BuildQueryString() QueryParameters["$filter"] = FilterBuilder.BuildFilterString(); } - if (SearchTerm != null) { + if (SearchTerm != null) + { QueryParameters["searchTerm"] = SearchTerm; } - foreach (var parameter in AdditionalParameters) + foreach (KeyValuePair parameter in AdditionalParameters) { QueryParameters[parameter.Key] = parameter.Value; } @@ -147,13 +148,13 @@ public string BuildFilterString() // Parenthesizing binary criteria (like "Id eq 'Foo'") would ideally provide better isolation/debuggability of mis-built filters. // However, a $filter like "(IsLatestVersion)" appears to be rejected by PSGallery (possibly because grouping operators cannot be used with single unary operators). - // Parenthesizing only binary criteria requires more introspection into the underlying criteria, which we don't currently have with string-form criteria. + // Parenthesizing only binary criteria requires more introspection into the underlying criteria, which we don't currently have with string-form criteria. // Figure out the expected size of our filter string, based on: int ExpectedSize = FilterCriteria.Select(x => x.Length).Sum() // The length of the filter criteria themselves. + 5 * (FilterCriteria.Count - 1); // The length of the combining string, " and ", interpolated between the filters. - // Allocate a StringBuilder with our calculated capacity. + // Allocate a StringBuilder with our calculated capacity. // This helps right-size memory allocation and reduces performance impact from resizing the builder's internal capacity. StringBuilder sb = new StringBuilder(ExpectedSize); @@ -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 e62d15e77..b609bd720 100644 --- a/src/code/V2ResponseUtil.cs +++ b/src/code/V2ResponseUtil.cs @@ -40,7 +40,7 @@ public override IEnumerable ConvertToPSResourceResult(FindResu foreach (string response in responses) { - var elemList = ConvertResponseToXML(response); + XmlNode[] elemList = ConvertResponseToXML(response); if (elemList.Length == 0) { // this indicates we got a non-empty, XML response (as noticed for V2 server) but it's not a response that's meaningful (contains 'properties') @@ -49,7 +49,7 @@ public override IEnumerable ConvertToPSResourceResult(FindResu yield return new PSResourceResult(returnedObject: null, exception: notFoundException, isTerminatingError: false); } - foreach (var element in elemList) + foreach (XmlNode element in elemList) { if (!PSResourceInfo.TryConvertFromXml(element, out PSResourceInfo psGetInfo, Repository, out string errorMsg)) { @@ -72,7 +72,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; @@ -89,13 +90,13 @@ public XmlNode[] ConvertResponseToXML(string httpResponse) { { XmlNode node = entryNode[i]; nodes[i] = node; - var entryChildNodes = node.ChildNodes; + XmlNodeList entryChildNodes = node.ChildNodes; foreach (XmlElement childNode in entryChildNodes) { var entryKey = childNode.LocalName; if (entryKey.Equals("properties")) { - var propertyChildNodes = childNode.ChildNodes; + XmlNodeList propertyChildNodes = childNode.ChildNodes; foreach (XmlElement propertyChild in propertyChildNodes) { var propertyKey = propertyChild.LocalName; diff --git a/src/code/V2ServerAPICalls.cs b/src/code/V2ServerAPICalls.cs index 94d0b3a0b..2e5c13bf2 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); @@ -347,16 +351,18 @@ public override FindResults FindName(string packageName, bool includePrerelease, { "$inlinecount", "allpages" }, { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; // 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); } /// @@ -416,16 +422,18 @@ public override FindResults FindNameWithTag(string packageName, string[] tags, b { "$inlinecount", "allpages" }, { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; // 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)); } @@ -642,16 +650,18 @@ public override FindResults FindVersion(string packageName, string version, Reso { "$inlinecount", "allpages" }, { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; // 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)); } @@ -708,17 +718,19 @@ public override FindResults FindVersionWithTag(string packageName, string versio { "$inlinecount", "allpages" }, { "id", $"'{packageName}'" }, }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; // We need to explicitly add 'Id eq ' whenever $filter is used, otherwise arbitrary results are returned. // 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)); } @@ -906,31 +918,40 @@ private string FindAllFromTypeEndPoint(bool includePrerelease, bool isSearchingM { "$skip", skip.ToString()}, { "$top", "6000"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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"); } } @@ -958,27 +979,35 @@ private string FindTagFromEndpoint(string[] tags, bool includePrerelease, bool i { "$skip", skip.ToString()}, { "$top", "6000"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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"); } @@ -1008,28 +1037,36 @@ private string FindCommandOrDscResource(string[] tags, bool includePrerelease, b { "$skip", skip.ToString()}, { "$top", "6000"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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"); } @@ -1063,34 +1100,42 @@ private string FindNameGlobbing(string packageName, ResourceType type, bool incl { "$skip", skip.ToString()}, { "$top", "100"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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()}"; @@ -1171,35 +1217,43 @@ private string FindNameGlobbingWithTag(string packageName, string[] tags, Resour { "$skip", skip.ToString()}, { "$top", "100"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder 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()}"; @@ -1313,7 +1368,7 @@ private string FindVersionGlobbing(string packageName, VersionRange versionRange {"id", $"'{packageName}'"} }); - var filterBuilder = queryBuilder.FilterBuilder; + NuGetV2FilterBuilder filterBuilder = queryBuilder.FilterBuilder; if (versionRange.MinVersion != null) { @@ -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"); } @@ -1400,7 +1459,7 @@ private Stream InstallVersion(string packageName, string version, out ErrorRecor requestUrlV2 = $"{Repository.Uri}/package/{packageName}/{version}"; } - var response = HttpRequestCallForContent(requestUrlV2, out errRecord); + HttpContent response = HttpRequestCallForContent(requestUrlV2, out errRecord); if (errRecord != null) { @@ -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 903b1da55..a4522ccba 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"; @@ -58,7 +58,8 @@ public V3ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, Ne 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); @@ -374,14 +378,14 @@ private FindResults FindNameGlobbingFromNuGetRepo(string packageName, string[] t return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType); } - var matchingPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(querySearchTerm, includePrerelease, out errRecord); + List matchingPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(querySearchTerm, includePrerelease, out errRecord); if (errRecord != null) { return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType); } List matchingResponses = new List(); - foreach (var pkgEntry in matchingPkgEntries) + foreach (JsonElement pkgEntry in matchingPkgEntries) { string id = string.Empty; string latestVersion = string.Empty; @@ -454,7 +458,7 @@ private FindResults FindTagsFromNuGetRepo(string[] tags, bool includePrerelease, string tagsQueryTerm = $"tags:{String.Join(" ", tags)}"; // Get responses for all packages that contain the required tags // example query: - var tagPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(tagsQueryTerm, includePrerelease, out errRecord); + List tagPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(tagsQueryTerm, includePrerelease, out errRecord); if (errRecord != null) { return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType); @@ -472,7 +476,7 @@ private FindResults FindTagsFromNuGetRepo(string[] tags, bool includePrerelease, } List matchingPkgResponses = new List(); - foreach (var pkgEntry in tagPkgEntries) + foreach (JsonElement pkgEntry in tagPkgEntries) { matchingPkgResponses.Add(pkgEntry.ToString()); } @@ -780,7 +784,7 @@ private Stream InstallHelper(string packageName, NuGetVersion version, out Error return null; } - var content = HttpRequestCallForContent(pkgContentUrl, out errRecord); + HttpContent content = HttpRequestCallForContent(pkgContentUrl, out errRecord); if (errRecord != null) { return null; @@ -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()); @@ -1197,7 +1202,7 @@ private string[] GetMetadataElementsFromResponse(string response, string propert } // Loop through inner "items" entries we collected, and get the specific entry for each package version - foreach (var item in innerItemsElements) + foreach (JsonElement item in innerItemsElements) { if (!item.TryGetProperty(property, out JsonElement metadataElement)) { @@ -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 c45e6d05a..a4398b8b3 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 e372720b0..d69a8b465 100644 --- a/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 +++ b/test/FindPSResourceTests/FindPSResourceContainerRegistryServer.Tests.ps1 @@ -313,10 +313,10 @@ Describe 'Test Find-PSResource for MAR Repository' -tags 'CI' { It "Should find version range for Az dependencies" { # Target known version to know the output from the API won't change $res = Find-PSResource -Repository 'MAR' -Name 'Az' -Version '14.4.0' - + # Version defined by "ModuleVersion" $res.Dependencies.Where{$_.'Name' -eq 'Az.Accounts'}.'VersionRange'.ToString() | Should -Be '[5.3.0, )' - + # Version defined by "RequiredVersion" $res.Dependencies.Where{$_.'Name' -eq 'Az.Resources'}.'VersionRange'.ToString() | Should -Be '[8.1.0, 8.1.0]' } diff --git a/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceGithubPackages.Tests.ps1 index 30512d7f7..7cc5f77dc 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 a3cbe2335..3d91c5763 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" @@ -120,18 +120,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"} + $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 $localRepo @@ -219,8 +219,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" } @@ -240,8 +239,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] diff --git a/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceRepositorySearching.Tests.ps1 index 4f010de2f..9b72864e2 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" @@ -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] @@ -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 @@ -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 with 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 } } @@ -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 } } @@ -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 139e68ab0..660a6bceb 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" $testScriptName = "test_script" @@ -44,10 +44,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 } } @@ -60,18 +58,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 @@ -131,24 +129,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" } @@ -189,8 +179,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 } } @@ -247,8 +236,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 } @@ -267,8 +255,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] @@ -450,7 +437,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 @@ -459,9 +446,9 @@ Describe 'Test HTTP Find-PSResource for V2 Server Protocol' -tags 'ManualValidat AfterAll { Get-RevertPSResourceRepositoryFile } - It "find resource given CommandName" { - $res = Find-PSResource -Name $testModuleName -Repository $PSGalleryName -Type Module + It "find module by name" { + $res = Find-PSResource -Name $testModuleName -Repository $PSGalleryName -Type Module $res.Name | Should -Be $testModuleName } @@ -471,15 +458,12 @@ 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 } - - $foundPkgs.Add($item.Name) + $null = $foundPkgs.Add($item.Name) } $duplicatePkgsFound | Should -BeFalse diff --git a/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 b/test/FindPSResourceTests/FindPSResourceV3Server.Tests.ps1 index b216ecd71..2b95b3313 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 5ddbf816a..45d61b890 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" @@ -52,10 +52,10 @@ 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 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 260696870..6a90ade42 100644 --- a/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceADOServer.Tests.ps1 @@ -25,9 +25,9 @@ Describe 'Test Install-PSResource for ADO 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 ADO 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 614131b30..763b2d47f 100644 --- a/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceADOV2Server.Tests.ps1 @@ -25,9 +25,9 @@ Describe 'Test Install-PSResource for ADO V2Server 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 ADO V2Server 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 afe81d2c3..3a2886aeb 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 7f38f05b3..f642bf0d0 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) @@ -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" diff --git a/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 b/test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1 index 77c8766ad..b937b3abf 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 46d4c54a6..733a74553 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" @@ -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,7 +93,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 "not install resource and write error if resource does not exist in any pattern matching repositories (-Repository with wildcard)" { @@ -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 6023355b7..5d078abad 100644 --- a/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 +++ b/test/InstallPSResourceTests/InstallPSResourceV2Server.Tests.ps1 @@ -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 e18b9272d..78e7470a6 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' 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 c7c452a43..5fd8fbf0a 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 75205069e..6962f1a40 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 @@ -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 @@ -396,7 +391,7 @@ 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" diff --git a/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 b/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 index e97f64407..8ffc064af 100644 --- a/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 +++ b/test/PublishPSResourceTests/PublishPSResource.Tests.ps1 @@ -63,17 +63,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 +81,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 } @@ -103,7 +100,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:PSGalleryName = 'PSGallery' } AfterAll { - Get-RevertPSResourceRepositoryFile + Get-RevertPSResourceRepositoryFile } AfterEach { # Delete all contents of the repository without deleting the repository directory itself @@ -151,7 +148,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" @@ -207,9 +204,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" @@ -265,7 +262,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 @@ -293,7 +290,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" { @@ -514,23 +511,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 @@ -567,7 +564,7 @@ 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 @@ -644,14 +641,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" { @@ -659,7 +656,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'" { @@ -691,7 +688,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" 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 9714a627c..e38a37cc1 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 } @@ -104,8 +98,7 @@ Describe "Test Publish-PSResource" -tags 'CI' { $script:PSGalleryName = "PSGallery" } AfterEach { - if(!(Test-Path $script:PublishModuleBase)) - { + if (!(Test-Path $script:PublishModuleBase)) { Remove-Item -Path $script:PublishModuleBase -Recurse -Force } } @@ -346,21 +339,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 @@ -406,7 +399,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 @@ -501,7 +494,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 93df34b22..78478d709 100644 --- a/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 +++ b/test/ResourceRepositoryTests/RegisterPSResourceRepository.Tests.ps1 @@ -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 @@ -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 @@ -376,7 +376,7 @@ 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 @@ -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 fa9120dfe..54d972c46 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 -Verbose @@ -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 -Verbose -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/SavePSResourceLocal.Tests.ps1 b/test/SavePSResourceTests/SavePSResourceLocal.Tests.ps1 index 5b090e739..4878a769f 100644 --- a/test/SavePSResourceTests/SavePSResourceLocal.Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceLocal.Tests.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 @@ -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 diff --git a/test/SavePSResourceTests/SavePSResourceV2.Tests.ps1 b/test/SavePSResourceTests/SavePSResourceV2.Tests.ps1 index 609c73e3d..4c3705a75 100644 --- a/test/SavePSResourceTests/SavePSResourceV2.Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceV2.Tests.ps1 @@ -105,11 +105,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 @@ -128,7 +127,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 @@ -138,7 +137,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/SavePSResourceV3.Tests.ps1 b/test/SavePSResourceTests/SavePSResourceV3.Tests.ps1 index 037ed1674..c8470cee7 100644 --- a/test/SavePSResourceTests/SavePSResourceV3.Tests.ps1 +++ b/test/SavePSResourceTests/SavePSResourceV3.Tests.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 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 0a1fa10fc..5925805b2 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) @@ -144,11 +144,11 @@ Describe 'Test Uninstall-PSResource for Modules' -tags 'CI' { 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 } diff --git a/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 b/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 index b922b38c4..79bba5761 100644 --- a/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 +++ b/test/UpdateModuleManifest/UpdateModuleManifest.Tests.ps1 @@ -59,7 +59,7 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { } 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 @@ -70,13 +70,12 @@ Describe 'Test Update-PSModuleManifest' -tags 'CI' { 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" { @@ -359,14 +358,14 @@ 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 diff --git a/test/UpdatePSResourceTests/UpdatePSResourceLocal.Tests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceLocal.Tests.ps1 index f5334be83..37e05c640 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceLocal.Tests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceLocal.Tests.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/UpdatePSResourceV2.Tests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceV2.Tests.ps1 index 07db15035..6ee625708 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceV2.Tests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceV2.Tests.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 } } @@ -82,10 +75,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 } } @@ -93,18 +84,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 @@ -115,10 +106,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 @@ -127,10 +118,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 } } @@ -162,10 +151,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 } @@ -180,10 +167,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 } @@ -198,10 +183,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 } @@ -221,10 +204,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 } @@ -253,10 +234,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 } @@ -277,10 +256,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 } @@ -301,10 +278,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 } @@ -325,10 +300,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 } @@ -361,10 +334,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/UpdatePSResourceV3.Tests.ps1 b/test/UpdatePSResourceTests/UpdatePSResourceV3.Tests.ps1 index 88ed957dc..26a026d13 100644 --- a/test/UpdatePSResourceTests/UpdatePSResourceV3.Tests.ps1 +++ b/test/UpdatePSResourceTests/UpdatePSResourceV3.Tests.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..4b30b1ef7 100644 --- a/test/perf/benchmarks/README.md +++ b/test/perf/benchmarks/README.md @@ -1,32 +1,37 @@ -## Micro Benchmarks +# Micro Benchmarks This folder contains micro benchmarks that test the performance of PSResourceGet. -### Quick Start +## 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] + ```bash + dotnet run -c Release -f net8.0 ``` -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 +1. To list all available benchmarks ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Listing-the-Benchmarks)): + + ```bash + dotnet run -c Release -f net8.0 --list [flat/tree] ``` -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)) +1. 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)]): + + ```bash + dotnet run -c Release -f net8.0 --filter *script* --list flat ``` - dotnet run -c Release -f net6.0 --filter *script* --profiler ETW + +1. To profile the benchmarked code and produce an ETW Trace file ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Profiling)) + + ```bash + dotnet run -c Release -f net8.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..3a9934f8e 100644 --- a/test/perf/benchmarks/benchmarks.csproj +++ b/test/perf/benchmarks/benchmarks.csproj @@ -1,6 +1,6 @@ - net6.0 + net8.0 Exe @@ -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..aec967900 100644 --- a/tool/releaseTools.psm1 +++ b/tool/releaseTools.psm1 @@ -19,9 +19,9 @@ function Update-Branch { [CmdletBinding(SupportsShouldProcess)] param() $Branch = git branch --show-current - if ($Branch -ne "release") { - if ($PSCmdlet.ShouldProcess("release", "git checkout -B")) { - git checkout -B "release" + if ($Branch -ne 'release') { + if ($PSCmdlet.ShouldProcess('release', 'git checkout -B')) { + git checkout -B 'release' } } } @@ -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($_) } } @@ -73,13 +75,13 @@ function Set-Changelog { ) @( "## $Version" - "" - "### New Features" + '' + '### New Features' $script:NewFeatures - "" - "### Bug Fixes" + '' + '### Bug Fixes' $script:BugFixes - "" + '' ) } @@ -113,17 +115,17 @@ function Update-PSDFile { [Parameter(Mandatory)] [string]$Version ) - $CurrentPSDFile = Get-Content -Path ".\src\PSResourceGet.psd1" - $Header = $CurrentPSDFile.Where({$_.StartsWith("## ")}, "First") + $CurrentPSDFile = Get-Content -Path '.\src\PSResourceGet.psd1' + $Header = $CurrentPSDFile.Where({ $_.StartsWith('## ') }, 'First') @( - $CurrentPSDFile.Where({ $_ -eq $Header }, "Until") + $CurrentPSDFile.Where({ $_ -eq $Header }, 'Until') Set-Changelog $Version - $CurrentPSDFile.Where({ $_ -eq $Header }, "SkipUntil") - ) | Set-Content -Encoding utf8NoBOM -Path ".\src\PSResourceGet.psd1" + $CurrentPSDFile.Where({ $_ -eq $Header }, 'SkipUntil') + ) | Set-Content -Encoding utf8NoBOM -Path '.\src\PSResourceGet.psd1' - if ($PSCmdlet.ShouldProcess(".\src\PSResourceGet.psd1", "git add")) { - git add "src\PSResourceGet.psd1" + if ($PSCmdlet.ShouldProcess('.\src\PSResourceGet.psd1', 'git add')) { + git add 'src\PSResourceGet.psd1' } } @@ -142,22 +144,22 @@ function New-ReleasePR { ) Update-Branch - if ($PSCmdlet.ShouldProcess("$script:ChangelogFile", "git commit")) { + if ($PSCmdlet.ShouldProcess("$script:ChangelogFile", 'git commit')) { git add $ChangelogFile git commit -m "Update CHANGELOG for ``$Version``" } - if ($PSCmdlet.ShouldProcess("release", "git push")) { - Write-Host "Pushing release branch..." + if ($PSCmdlet.ShouldProcess('release', 'git push')) { + Write-Host 'Pushing release branch...' git push --force-with-lease origin release } $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 { -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..b24dbd198 100644 --- a/tool/setupReleaseTools.ps1 +++ b/tool/setupReleaseTools.ps1 @@ -6,12 +6,12 @@ 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" +Write-Host 'Setup authentication' Set-GitHubConfiguration -SuppressTelemetryReminder $password = ConvertTo-SecureString -String $Token -AsPlainText -Force -Set-GitHubAuthentication -Credential (New-Object System.Management.Automation.PSCredential ("token", $password)) +Set-GitHubAuthentication -Credential (New-Object System.Management.Automation.PSCredential ('token', $password))