diff --git a/.editorconfig b/.editorconfig index 0e47235a0d7..2d1de09be0c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,11 +11,25 @@ insert_final_newline = true indent_style = space indent_size = 4 trim_trailing_whitespace = true +spelling_exclusion_path = exclusion.dic # JSON files [*.json] indent_size = 2 +# Xml config files +[*.{props,targets,config,nuspec}] +indent_size = 2 + +# Xml files +[*.{xml,stylecop,resx,ruleset}] +indent_size = 2 + +# Xml project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}] +charset = utf-8 +indent_size = 2 + # Generated code [*{_AssemblyInfo.cs,.notsupported.cs}] generated_code = true diff --git a/.gitattributes b/.gitattributes index d63119fdc95..802b72d58bf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -56,4 +56,7 @@ *.jpg binary *.png binary -*.gif binary \ No newline at end of file +*.gif binary + +# VerifyTests +*.verified.txt text eol=lf working-tree-encoding=UTF-8 \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 957b316a7a1..9ab0dc20fc5 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,7 +1,7 @@ version: 2 updates: - package-ecosystem: "nuget" - directory: "/eng/dependabot" + directory: "/" open-pull-requests-limit: 10 schedule: interval: "weekly" @@ -9,13 +9,7 @@ updates: labels: - "dependencies" - "dependabot: main" - - - package-ecosystem: "nuget" - directory: "/eng/dependabot" - open-pull-requests-limit: 10 - schedule: - interval: "weekly" - target-branch: "release/7.0.4xx" - labels: - - "dependencies" - - "dependabot: 7.0.4xx" + ignore: + - dependency-name: "Microsoft.*" + - dependency-name: "NuGet.*" + - dependency-name: "System.*" \ No newline at end of file diff --git a/.gitignore b/.gitignore index 4c12bd0b08c..d7488adadf1 100644 --- a/.gitignore +++ b/.gitignore @@ -22,8 +22,9 @@ bld/ [Bb]in/ [Oo]bj/ dev/ +*.binlog -# Visual Studio 2015 cache/options directory +# Visual Studio cache/options directory .vs/ # Visual Studio launch settings **/launchSettings.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000000..be9d3065da9 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Run template scanner", + "type": "coreclr", + "request": "launch", + "program": "${workspaceFolder}\\artifacts\\bin\\Microsoft.TemplateSearch.TemplateDiscovery\\Debug\\net9.0\\Microsoft.TemplateSearch.TemplateDiscovery.dll", + "args": [ + "--basePath", + "./templates", + "--verbose", + "--savePacks", + "--diff", + "true", + "--test", + "--allowPreviewPacks" + ] + } + ] +} \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS index 7f830a8550c..c402bfc3085 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1,4 +1,4 @@ * @dotnet/templating-engine-maintainers -/docs/ @dotnet/templating-engine-maintainers @baronfel -/eng/ @dotnet/templating-engine-maintainers @GangWang01 -global.json @dotnet/templating-engine-maintainers @GangWang01 +/docs/ @dotnet/templating-engine-maintainers +/eng/ @dotnet/templating-engine-maintainers +global.json @dotnet/templating-engine-maintainers diff --git a/Directory.Build.props b/Directory.Build.props index 3d5fc97267d..ee780122bdb 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,38 +1,37 @@ - - - - - preview - net8.0 - netstandard2.0 - net472 - Microsoft .NET Core - $(CopyrightNetFoundation) - MIT - true - NU5105;NU5128;NU5100;NU5118;0419,0649 - true - true - true - enable - + - - true - $(RepoRoot)build\ - $(RepoRoot)artifacts\ - $(RepoRoot)dev\ - $(RepoRoot)tools\ - $(RepoRoot).tools\ - $(RepoRoot)localize\ - $(RepoRoot)template_feed\ - $(RepoRoot)src\ - $(RepoRoot)test\ - MicrosoftAspNetCore - 0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb - 0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7 - + + preview + Microsoft .NET + $(CopyrightNetFoundation) + MIT + true + $(NoWarn);NU5105;NU5128;NU5100;NU5118;0419,0649 + true + true + true + enable + enable + + true + $(RepoRoot)tools\ + $(RepoRoot)template_feed\ + $(RepoRoot)src\ + $(RepoRoot)test\ + MicrosoftAspNetCore + 0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb + 0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7 + + true + + false + + + + + + diff --git a/Directory.Build.targets b/Directory.Build.targets index 2ec401282fd..df64f2c06a9 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,14 +1,10 @@ - - - + - - + + - - diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000000..e765497749f --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,60 @@ + + + + true + true + + $(NoWarn);NU1507 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt index 3e764f4cb8a..a616ed188df 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 .NET Foundation +Copyright (c) .NET Foundation and Contributors All rights reserved. @@ -20,4 +20,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +SOFTWARE. \ No newline at end of file diff --git a/Loc.Settings.targets b/Loc.Settings.targets deleted file mode 100644 index 8a25f6594a3..00000000000 --- a/Loc.Settings.targets +++ /dev/null @@ -1,110 +0,0 @@ - - - $(MSBuildThisFileDirectory)localize\Templating.loc.props - - - - all - - - - $(Lang) - $(Lang) - $(MSBuildThisFileDirectory).tools\loc - $(MSBuildThisFileDirectory)localize - $(LocPath)\comments - $(LocToolsPath)\lsbuild.exe - ploc;chs;cht;deu;esn;fra;ita;jpn;kor;rus;ptb;plk;csy;trk - PLOC;CHS;CHT;DEU;ESN;FRA;ITA;JPN;KOR;RUS;PTB;PLK;CSY;TRK - Full - Pseudo - $(MSBuildThisFileDirectory)dev\ - $(MSBuildThisFileDirectory)artifacts\localize\ - $(MSBuildThisFileDirectory)obj - - - - - zh-Hans - 2052 - zh-CN - - - zh-Hant - 1028 - zh-TW - - - cs - 1029 - cs-CZ - - - de - 1031 - de-DE - - - en - 1033 - en-US - - - es - 3082 - es-ES - - - fr - 1036 - fr-FR - - - it - 1040 - it-IT - - - ja - 1041 - ja-JP - - - ko - 1042 - ko-KR - - - pl - 1045 - pl-PL - - - pt-BR - 1046 - pt-BR - - - ru - 1049 - ru-RU - - - tr - 1055 - tr-TR - - - JPN - JPN - ja - ja-JP - 1041 - Pseudo - - - - - $(LocPath)\$(SrcLocale) - - diff --git a/Microsoft.TemplateEngine.sln b/Microsoft.TemplateEngine.sln index 49daee61ba9..1f16c0a9e47 100644 --- a/Microsoft.TemplateEngine.sln +++ b/Microsoft.TemplateEngine.sln @@ -62,6 +62,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .editorconfig = .editorconfig Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets + exclusion.dic = exclusion.dic + Directory.Packages.props = Directory.Packages.props EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{B794BF86-4185-4DCE-AC86-C27D5D966B9B}" diff --git a/NuGet.config b/NuGet.config index d0ff87cda9f..40e7c9a2e2c 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,19 +2,12 @@ - - - - + - - - - - - + + diff --git a/README.md b/README.md index 133c3d4509b..2d3f87213ff 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The key packages are: `dotnet new` CLI is now located in [dotnet/sdk](https://github.com/dotnet/sdk/tree/main/src/Cli/Microsoft.TemplateEngine.Cli) repo. -The issues for `dotnet new` CLI UX should be opened in the that repository. +The issues for `dotnet new` CLI UX should be opened in that repository. ### Template Content Repositories @@ -41,6 +41,7 @@ The templates are located in the following repositories: |Common project and item templates|[dotnet/sdk](https://github.com/dotnet/sdk)| |ASP.NET and Blazor templates|[dotnet/aspnetcore](https://github.com/dotnet/aspnetcore)| |ASP.NET Single Page Application templates| [dotnet/spa-templates](https://github.com/dotnet/spa-templates)| +|Aspire templates|[dotnet/aspire](https://github.com/dotnet/aspire)| |WPF templates|[dotnet/wpf](https://github.com/dotnet/wpf)| |Windows Forms templates|[dotnet/winforms](https://github.com/dotnet/winforms)| |Test templates|[dotnet/test-templates](https://github.com/dotnet/test-templates)| diff --git a/azure-pipelines-pr.yml b/azure-pipelines-pr.yml index f13acc248d6..3064dbe40c4 100644 --- a/azure-pipelines-pr.yml +++ b/azure-pipelines-pr.yml @@ -54,6 +54,8 @@ stages: enablePublishBuildAssets: true enablePublishUsingPipelines: ${{ variables._PublishUsingPipelines }} enableSourceBuild: true + sourceBuildParameters: + enableInternalSources: true enableTelemetry: true helixRepo: dotnet/templating jobs: @@ -71,7 +73,6 @@ stages: # Only enable publishing in non-public, non PR scenarios. - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - # DotNet-Symbol-Server-Pats provides: microsoft-symbol-server-pat, symweb-symbol-server-pat # Publish-Build-Assets provides: MaestroAccessToken, BotAccount-dotnet-maestro-bot-PAT - group: Publish-Build-Assets - _InternalBuildArgs: /p:DotNetSignType=$(_SignType) /p:TeamName=$(_TeamName) @@ -95,6 +96,7 @@ stages: steps: - checkout: self clean: true + # Use utility script to run script command dependent on agent OS. - script: eng/common/cibuild.cmd -configuration $(_BuildConfig) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9f932707765..94ea9ca7d55 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -80,6 +80,8 @@ extends: enablePublishBuildAssets: true enablePublishUsingPipelines: ${{ variables._PublishUsingPipelines }} enableSourceBuild: true + sourceBuildParameters: + enableInternalSources: true enableTelemetry: true helixRepo: dotnet/templating jobs: @@ -108,6 +110,7 @@ extends: steps: - checkout: self clean: true + # Use utility script to run script command dependent on agent OS. - script: eng/common/cibuild.cmd -configuration $(_BuildConfig) diff --git a/build.cmd b/build.cmd index 197ba099fd0..c099b981181 100644 --- a/build.cmd +++ b/build.cmd @@ -1,3 +1,3 @@ @echo off -powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\common\Build.ps1""" -build -restore -pack -test %*" +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\common\Build.ps1""" -restore -build -pack -test %*" exit /b %ErrorLevel% diff --git a/build.sh b/build.sh index 297d102ad2c..8e3e6948465 100755 --- a/build.sh +++ b/build.sh @@ -13,4 +13,4 @@ while [[ -h $source ]]; do done scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" -"$scriptroot/eng/common/build.sh" --pack --build --restore --test $@ \ No newline at end of file +"$scriptroot/eng/common/build.sh" --restore --build --pack --test $@ \ No newline at end of file diff --git a/docs/Available-Symbols-Generators.md b/docs/Available-Symbols-Generators.md index 0416abb5ac8..1d47d8234d7 100644 --- a/docs/Available-Symbols-Generators.md +++ b/docs/Available-Symbols-Generators.md @@ -53,7 +53,7 @@ This is a sample of definition of a generated symbol, the `port` generator, that }, ``` -Most of the generators need to be configured via parameters that let you select the source of the data and select among the options available. Below is a sample of a symbol that use the `now` generator to replace a fixed year indication present in the source files with the current year. +Most of the generators need to be configured via parameters that let you select the source of the data and select among the options available. Below is a sample of a symbol that uses the `now` generator to replace a fixed year indication present in the source files with the current year. ```json "copyrightYear": { @@ -643,14 +643,14 @@ This sample will rename folder called `Api` into `Source/Api/Microsoft/Visual St `Program.cs`: ```C# -// This file is generated for platfrom: SupportedPlatforms +// This file is generated for platform: SupportedPlatforms ``` This sample will expand and join values of `Platform` argument and replace `SupportedPlatforms` string with `MacOS, iOS`: `Program.cs`: ```C# -// This file is generated for platfrom: MacOS, iOS +// This file is generated for platform: MacOS, iOS ``` ### Related diff --git a/docs/Binding-and-project-context-evaluation.md b/docs/Binding-and-project-context-evaluation.md index f4ce729bfa8..a951d7936b1 100644 --- a/docs/Binding-and-project-context-evaluation.md +++ b/docs/Binding-and-project-context-evaluation.md @@ -9,7 +9,7 @@ The feature is available for both `dotnet new` and Visual Studio. The symbol binds value from external sources. By default, the following sources are available: -- host parameters - parameters defined at certain host. For .NET SDK the following parameters are defined: `HostIdentifier: dotnetcli`, `GlobalJsonExists: true/false`. Binding syntax is `host:`, example: `host:HostIdentifier`. +- host parameters - parameters defined at certain host. For .NET SDK the following parameters are defined: `HostIdentifier: dotnetcli`, `GlobalJsonExists: true/false`, `WorkingDirectory: `. Binding syntax is `host:`, example: `host:HostIdentifier`. - environment variables - allows to bind environment variables. Binding syntax is `env:`, example: `env:MYENVVAR`. It is also possible to bind the parameter without the prefix as a fallback behavior: `HostIdentifier`, `MYENVVAR`. @@ -37,6 +37,10 @@ The higher value indicates higher priority. "HostIdentifier": { "type": "bind", "binding": "host:HostIdentifier" + }, + "WorkingDirectory": { + "type": "bind", + "binding": "host:WorkingDirectory" } } ``` diff --git a/docs/Conditional-processing-and-comment-syntax.md b/docs/Conditional-processing-and-comment-syntax.md index ef3ff498e85..7d5bdab847a 100644 --- a/docs/Conditional-processing-and-comment-syntax.md +++ b/docs/Conditional-processing-and-comment-syntax.md @@ -41,7 +41,7 @@ ## Introduction -To add conditional, or dynamic, content you can add Template Engine expressions in your source files. The conditional expression let you to include or exclude part of the file according to a specified condition, and to do this you can use the familiar conditional expressions like **#if**, **#else**, **#elseif**, **#endif**. +To add conditional, or dynamic, content you can add Template Engine expressions in your source files. The conditional expression lets you include or exclude part of the file according to a specified condition, and to do this you can use the familiar conditional expressions like **#if**, **#else**, **#elseif**, **#endif**. To learn more about conditional expressions evaluation go to [Conditions](Conditions.md) description. @@ -310,7 +310,7 @@ The first expression is not emitted because it is processed, and the condition e ## JSON Files For .json files, the comment block starts with `//` or `////` to the end of the line. After this marker you can add the conditional expressions. -The choice between `//` or `////` is very important because let you choose between different actions to be executed when the condition is met: in the first case the content in the expression is simply rendered into the output files as is, while in the second a different action can be excuted, by default uncommenting removing an eventual leading `//`. +The choice between `//` or `////` is very important because it lets you choose between different actions to be executed when the condition is met: in the first case the content in the expression is simply rendered into the output files as is, while in the second a different action can be executed, by default uncommenting removing an eventual leading `//`. #### File Extensions @@ -399,7 +399,7 @@ MSBuild files, in addition to the `#if`, `#else`, `#elseif`, `#endif` inside an ### Samples -In this sample, one **** element will be added according to the value of the **TargetFrameworkOverride** symbol. This syntax is more clear and let you to use a single conditional expression to rule the inclusion of a whole block of content inside the template +In this sample, one **** element will be added according to the value of the **TargetFrameworkOverride** symbol. This syntax is more clear and lets you use a single conditional expression to rule the inclusion of a whole block of content inside the template ```xml netcoreapp2.0 @@ -416,7 +416,7 @@ In this sample, we can see that if the **TargetFrameworkOverride** symbol is def ``` -In this snippet of MSBuild file, we see usage of conditional expression embeded inside a xml comment. +In this snippet of MSBuild file, we see usage of conditional expression embedded inside a xml comment. ```xml diff --git a/docs/Conditions.md b/docs/Conditions.md index 7efba687041..5e919652d82 100644 --- a/docs/Conditions.md +++ b/docs/Conditions.md @@ -15,7 +15,7 @@ ## Overview -Conditions are used to drive [dynamic content genarating or replacing](Conditional-processing-and-comment-syntax.md). +Conditions are used to drive [dynamic content generating or replacing](Conditional-processing-and-comment-syntax.md). Conditions use C++ style of [conditional preprocessor expressions](https://docs.microsoft.com/en-us/cpp/preprocessor/hash-if-hash-elif-hash-else-and-hash-endif-directives-c-cpp?view=msvc-170). Expressions are composed from constant literals (strings, numbers, `true`, `false`), [operators](https://github.com/dotnet/templating/blob/main/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/Operator.cs), [symbols](https://github.com/dotnet/templating/blob/main/docs/Available-Symbols-Generators.md), brackets and whitespaces. Only single line expressions are supported. Boolean and numerical expressions are supported (nonzero value is interpreted as `true`) diff --git a/docs/Post-Action-Registry.md b/docs/Post-Action-Registry.md index bff07150a0b..ad5cab1160b 100644 --- a/docs/Post-Action-Registry.md +++ b/docs/Post-Action-Registry.md @@ -252,6 +252,50 @@ Includes a reference to `SomeDependency` into `MyProjectFile`. The referenced pr }] ``` +## Adding references to existing projects + +It is possible to add references to existing projects in your working directory. Since the name of the existing project is likely not a constant value for all template instantiations, a symbol can be used to pass the name of the existing project. + +The example below demonstrates how to add the existing project ```src/AlreadyExisting/AlreadyExisting.csproj``` as a reference to the template source project ```Project1/Project1.csproj```. + +``` +{ + "symbols": { + "existingProject": { + ... + "type": "parameter", + "datatype": "string", + "defaultValue": "ExistingProject/ExistingProject.csproj", + "fileRename": "ExistingProjectPath" // Must be same as targetFile + } + }, + "postActions": [ + { + "Description": "Add ProjectReference to ExistingProject/ExistingProject.csproj", + "applyFileRenamesToArgs": [ + "targetFiles" // Must be specified + ], + "args": { + "targetFiles": [ + "ExistingProjectPath" // Must be same as fileRename + ], + "referenceType": "project", + "reference": "Project1/Project1.csproj" + } + }] +} +``` + +The template above: +- Configures the ```existingProject``` parameter *symbol* with a ```fileRename``` configuration. +- Instructs the *'add reference to a project file'* post action to apply ```fileRename``` to the ```targetFiles``` argument. +- Uses the value passed to the ```existingProject``` *symbol* to replace the value of the matching ```targetFiles```. + +This template can be instantiated using: + +```dotnet new [templateName] --existingProject src/AlreadyExisting/AlreadyExisting.csproj``` + + # Add project(s) to a solution file - **Action ID** : `D396686C-DE0E-4DE6-906D-291CD29FC5DE` diff --git a/docs/Reference-for-template.json.md b/docs/Reference-for-template.json.md index 5e39742effc..9bcdba08135 100644 --- a/docs/Reference-for-template.json.md +++ b/docs/Reference-for-template.json.md @@ -21,7 +21,7 @@ the `template.json` file. This requires that a few changes have to be done on th ``` The templates can be packaged to a NuGet package for further distribution. -A tutorial on how to create the template package can be find [here](https://learn.microsoft.com/en-us/dotnet/core/tutorials/cli-templates-create-template-package). +A tutorial on how to create the template package can be found [here](https://learn.microsoft.com/en-us/dotnet/core/tutorials/cli-templates-create-template-package). |Category|Description| @@ -37,7 +37,7 @@ A tutorial on how to create the template package can be find [here](https://lear |`author`|The author of the template|no| |`classifications`| Zero or more characteristics of the template which are shown in the tabular output of `dotnet new list` and `dotnet new search` as "Tags". It is possible to filter the templates based on them using `--tag` option. In Visual Studio those items are shown in New Project Dialog in the available list of templates together with template name, description and language. Common classifications are: `Library`, `Test`, `Web` etc. |no| |`name`|The name for the template. This is displayed as the template name when using `dotnet new` and Visual Studio.|yes| -|`groupIdentity`|The ID of the group this template belongs to. This allows multiple templates to be displayed as one, with the the decision for which one to use based on the template options. |no| +|`groupIdentity`|The ID of the group this template belongs to. This allows multiple templates to be displayed as one, with the decision for which one to use based on the template options. See more information on templates grouping in [this article](./Using-Group-Identity.md). |no| |`tags`|You can use tags to improve the metadata of your project. Well-known tags are: `language` and `type`. To specify the template language, use the tag `language`. To specify the template type, use the tag `type`. Supported types are: `project`, `item`, `solution`.|no| |`shortName`|A name for selecting the template in CLI environment. This is the name shown as `Short Name` in `dotnet new` list of templates, and is the name to use to run this template. It is possible to specify multiple short names for the single template, and then any of them can be used to instantiate the template. The first element of the array is considered as the primary and first choice in scenarios where only single value is allowed (for example in tab completion of `dotnet new`). Be mindful when selecting the short name and using synonyms to avoid conflicts with other templates - the template short name should be unique. In case multiple template with the same short name are installed at the same time, the user won't be able to use any of them until one of the packages is uninstalled making the short name unique again. This doesn't apply for the templates that are part of the same group (have same `groupIdentity`). |yes| |`postActions`|Enables actions to be performed after the project is created. See [the article](Post-Action-Registry.md) on post actions for more details.|no| diff --git a/docs/Using-Group-Identity.md b/docs/Using-Group-Identity.md new file mode 100644 index 00000000000..f8b6be92740 --- /dev/null +++ b/docs/Using-Group-Identity.md @@ -0,0 +1,274 @@ +# Using group identity + +## What is group identity + +Template configuration features optional `groupIdentity` property. From `template.json` documentation, `groupIdentity` is the ID of the group this template belongs to. This allows multiple templates to be displayed as one, with the decision for which one to use based on the template options. + +It depends on template engine host implementation how `groupIdentity` is implemented. In this article, the implementation for dotnet CLI (`dotnet new`) will be explained. + +When developing the template, **it is important to create unique group identity to avoid clashes with other templates**. + +The are 2 typical use cases for using `groupIdentity`: + +- grouping the templates for different languages under the same short name + +Example: the console template for different languages +``` +> dotnet new list console +These templates matched your input: 'console' + +Template Name Short Name Language Tags +------------------------ ------------ ---------- ----------------- +Console App console [C#],F#,VB Common/Console + +``` + +- grouping the several templates under the same group identity that adds up different choice parameters to base template. The most known example for this use case is having `Framework` choice symbol listing supported frameworks for the template and implementing each supported framework in separate template. This also allows distributing different templates in different template packages if needed. + +When using groups, it is important to mention two other important properties from template configuration to pay attention too: +- `identity` - the template identity. **All the templates, including the individual templates in the template group, should have unique `identity`.** +- `precedence` - an integer value used to determine the precedence of this template among the other templates within the same group identity. The highest value is the preferred one. It is recommended to have different precedence values in all the templates in a group to avoid clashes during template resolution. + +## Use case #1: how to use group identity to group templates for different languages + +This is the most typical scenario for template groups. The example is a well-known console template. +The template can be defined for only one language, however in dotnet CLI we often see the templates for multiple languages as: +``` +> dotnet new list console +These templates matched your input: 'console' + +Template Name Short Name Language Tags +------------------------ ------------ ---------- ----------------- +Console App console [C#],F#,VB Common/Console + +``` +Typically, these are 3 individual templates put in the same template group. +You can see definition for this particular template here: [C# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-CSharp), [F# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-FSharp), [VB template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-VisualBasic). + +To define a similar scenario, you need the following configuration for your templates defined in template.json: + +C# template: +```json + "author": "Me", + "classifications": [ + "Common", + "Library" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "100", + "identity": "My.Awesome.Template.CSharp.1.0", + "shortName": "awesome", + "tags": { + "language": "C#", + }, + +``` +F# template: +```json + "author": "Me", + "classifications": [ + "Common", + "Library" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "100", + "identity": "My.Awesome.Template.FSharp.1.0", + "shortName": "awesome", + "tags": { + "language": "F#", + }, + +``` +VB template: +```json + "author": "Me", + "classifications": [ + "Common", + "Library" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "100", + "identity": "My.Awesome.Template.VB.1.0", + "shortName": "awesome", + "tags": { + "language": "VB", + }, + +``` + +With this configuration, after installed those templates will be shown in as +``` +> dotnet new list awesome +These templates matched your input: 'awesome' + +Template Name Short Name Language Tags +------------------------ ------------ ---------- ----------------- +My Awesome Template awesome [C#],F#,VB Common/Library + +``` + +The usage for those templates will be: +- `dotnet new awesome` - C# template will be run (as C# is default language) +- `dotnet new awesome --language F#` - F# template will be run +- `dotnet new awesome --language VB` - VB template will be run +- `dotnet new awesome --help` - the help for C# template will be shown (as C# is default language) +- `dotnet new awesome --help --language F#` - the help for F# template will be shown +- `dotnet new awesome --help --language VB` - the help for VB template will be shown + +The templates in a group may be distributed via multiple template packages. This means that the author is usually able to define the new template for another language and group them with existing or default ones (if the author knows the group identity). + +This means for previous example another author may define a different template for different language: +```json + "author": "You", + "classifications": [ + "Common" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "100", + "identity": "My.Awesome.Template.Cust.1.0", + "shortName": "awesome", + "tags": { + "language": "Cust", + }, + +``` +After new template is installed, it will be grouped together with templates: +``` +Template Name Short Name Language Author Tags +------------------------ ------------ ---------- ---------- ----------------- +My Awesome Template awesome [C#],F#,VB Me Common/Library + Cust You Common +``` + + +## Use case #2: how to use group identity to group templates with different choices in choice symbol + +This is more advanced scenario for the grouping, and it is not visible in dotnet CLI for final user. Microsoft templates are using this scenario to split the templates for different target frameworks for the following reasons: +- so they can be distributed separately +- the templates for different target frameworks may differ a lot. Defining them in a separate template makes the template definition easier. + +Console template is also one of such templates. You can see definition here: [8.0 C# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-CSharp), [7.0 C# template](https://github.com/dotnet/sdk/tree/release/7.0.1xx/template_feed/Microsoft.DotNet.Common.ProjectTemplates.7.0/content/ConsoleApplication-CSharp). + +To define a similar scenario, you need the following configuration for your templates defined in template.json: +.NET 8.0 C# template: +```json + "author": "Me", + "classifications": [ + "Common", + "Library" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "800", + "identity": "My.Awesome.Template.CSharp.8.0", + "shortName": "awesome", + "tags": { + "language": "C#", + }, + "symbols": { + "Framework": { + "type": "parameter", + "description": "The target framework for the project.", + "datatype": "choice", + "choices": [ + { + "choice": "net8.0", + "description": "Target net8.0", + "displayName": ".NET 8.0" + } + ], + "replaces": "net8.0", + "defaultValue": "net8.0", + "displayName": "Framework" + }, + } +``` +.NET 7.0 C# template: +```json + "author": "Me", + "classifications": [ + "Common", + "Library" + ], + "name": "My Awesome Template", + "groupIdentity": "My.Awesome.Template.GroupID", + "precedence": "700", + "identity": "My.Awesome.Template.CSharp.7.0", + "shortName": "awesome", + "tags": { + "language": "C#", + }, + "symbols": { + "Framework": { + "type": "parameter", + "description": "The target framework for the project.", + "datatype": "choice", + "choices": [ + { + "choice": "net7.0", + "description": "Target net7.0", + "displayName": ".NET 7.0" + } + ], + "replaces": "net7.0", + "defaultValue": "net7.0", + "displayName": "Framework" + }, + } +``` + +Note: +- these configurations have different precedence values, so in case `Framework` parameter is not specified, the .NET 8.0 template is run +- these configurations have same choice symbol `Framework` defined, and they have different choice values. + +With this configuration, after installed those templates will be shown in as +``` +> dotnet new list awesome +These templates matched your input: 'awesome' + +Template Name Short Name Language Tags +------------------------ ------------ ---------- ----------------- +My Awesome Template awesome [C#] Common/Library + +``` +Note, there is no indication that group contains 2 templates. + + +The usage for those templates will be: +- `dotnet new awesome` - .NET 8 template is run, as its precedence is higher. +- `dotnet new awesome --Framework net8.0` - .NET 8 template is run (same as above) +- `dotnet new awesome --Framework net7.0` - .NET 7 template is run. +- `dotnet new awesome --Framework net6.0` - this is error, as net6.0 choice is not defined. + +Note difference in showing help: +- `dotnet new awesome --help` - the combined help for both templates will be shown +``` +... +Template options: + -Framework The target framework for the project. + Type: choice + net8.0 Target net8.0 + net7.0 Target net7.0 + Default: net8.0 +... +``` + +Note down: +- in case the templates have different parameter symbols defined, all of them are shown in help +- the choice parameters contain combined choices from all the templates in the group (here, net8.0 from 1st template. net7.0 from 2nd template) +- the help is shown always for a particular template language. If you are combining this use case with use case #1 (grouping for different language), only the templates for selected language are combined when the help is shown. + +**When using this use case, it is very important to configure different precedence values in the template definition for all the templates in single template group. If any combination of template options results in more than one template resolved and their precedence values are not specified, or are the same, this combination is unusable and results in runtime error.** + +## Links +- [Reference for `template.json`](Reference-for-template.json.md) +- [`template.json` JSON schema](https://json.schemastore.org/template.json) +- [Template resolution for `dotnet new`](./template-resolution-for-dotnet-cli.md) +- Open issues: + - [#5358 Allow share template name for different languages](https://github.com/dotnet/templating/issues/5358) + - [#5844 Item templates should pick correct language from project](https://github.com/dotnet/templating/issues/5844) + - [#4135 Allow to pick up certain template group or certain template to be run in case of ambiguity](https://github.com/dotnet/templating/issues/4135) \ No newline at end of file diff --git a/dotnet-template-samples/Microsoft.TemplateEngine.Samples.csproj b/dotnet-template-samples/Microsoft.TemplateEngine.Samples.csproj index a51765feb52..9d1ba4ce15d 100644 --- a/dotnet-template-samples/Microsoft.TemplateEngine.Samples.csproj +++ b/dotnet-template-samples/Microsoft.TemplateEngine.Samples.csproj @@ -1,6 +1,7 @@ + - $(NETCoreTargetFramework) + $(NetCurrent) False False False @@ -9,7 +10,7 @@ true true true - 2008;NU5105 + $(NoWarn);2008;NU5105 true Microsoft.TemplateEngine.Samples Microsoft @@ -19,10 +20,9 @@ Template True + - - - content - + + diff --git a/dotnet-template-samples/content/03-optional-page/MyProject.StarterWeb/Program.cs b/dotnet-template-samples/content/03-optional-page/MyProject.StarterWeb/Program.cs index 59fc40c6c5b..c1956918e9b 100755 --- a/dotnet-template-samples/content/03-optional-page/MyProject.StarterWeb/Program.cs +++ b/dotnet-template-samples/content/03-optional-page/MyProject.StarterWeb/Program.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.AspNetCore.Hosting; namespace MyProject.StarterWeb diff --git a/dotnet-template-samples/content/17-rename-file/MyProject.Con/.template.config/template.json b/dotnet-template-samples/content/17-rename-file/MyProject.Con/.template.config/template.json new file mode 100644 index 00000000000..a52da260159 --- /dev/null +++ b/dotnet-template-samples/content/17-rename-file/MyProject.Con/.template.config/template.json @@ -0,0 +1,28 @@ +{ + "$schema": "http://json.schemastore.org/template", + "author": "Contoso", + "classifications": [ + "Console" + ], + "name": "Contoso Sample 17", + "identity": "MyProject.17.Sample.CSharp", + "groupIdentity": "MyProject.17.Sample", + "shortName": "sample17", + "tags": { + "language": "C#", + "type": "project" + }, + "symbols": { + "renameFileParameter": { + "type": "parameter", + "displayName": "File name", + "description": "Renames the default FileToRename.cs to the value provided.", + "datatype": "text", + "defaultValue": "FileToRename", + "replaces": "FileToRename", + "fileRename": "FileToRename" + } + }, + "sourceName": "MyProject.Con", + "preferNameDirectory": true +} \ No newline at end of file diff --git a/dotnet-template-samples/content/17-rename-file/MyProject.Con/FileToRename.cs b/dotnet-template-samples/content/17-rename-file/MyProject.Con/FileToRename.cs new file mode 100644 index 00000000000..47ed0bf71c9 --- /dev/null +++ b/dotnet-template-samples/content/17-rename-file/MyProject.Con/FileToRename.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace MyProject.Con; + +/// +/// The file FileToRename.cs will be renamed to the value of the renameFileParameter when the new template is used. +/// +public class FileToRename +{ +} diff --git a/tools/legacy-tools/ComparisonCleanup/ComparisonCleanup.csproj b/dotnet-template-samples/content/17-rename-file/MyProject.Con/MyProject.Con.csproj similarity index 64% rename from tools/legacy-tools/ComparisonCleanup/ComparisonCleanup.csproj rename to dotnet-template-samples/content/17-rename-file/MyProject.Con/MyProject.Con.csproj index 165515f30ff..120e38c3150 100644 --- a/tools/legacy-tools/ComparisonCleanup/ComparisonCleanup.csproj +++ b/dotnet-template-samples/content/17-rename-file/MyProject.Con/MyProject.Con.csproj @@ -2,7 +2,7 @@ Exe - $(NETCoreTargetFramework) + net7.0 diff --git a/dotnet-template-samples/content/17-rename-file/MyProject.Con/Program.cs b/dotnet-template-samples/content/17-rename-file/MyProject.Con/Program.cs new file mode 100644 index 00000000000..3afe4dfb8d6 --- /dev/null +++ b/dotnet-template-samples/content/17-rename-file/MyProject.Con/Program.cs @@ -0,0 +1,12 @@ +using System; + +namespace MyProject.Con +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Check the name of the file"); + } + } +} diff --git a/dotnet-template-samples/content/17-rename-file/README.md b/dotnet-template-samples/content/17-rename-file/README.md new file mode 100644 index 00000000000..1671f9608d6 --- /dev/null +++ b/dotnet-template-samples/content/17-rename-file/README.md @@ -0,0 +1,7 @@ +The sample in this folder demonstrates: + + - **How to rename a file and/or folder in your project template** + +See [`template.json`](./MyProject.Con/.template.config/template.json) +See [`FileToRename.cs`](./MyProject.Con/FileToRename.cs) + diff --git a/eng/Analyzers.props b/eng/Analyzers.props deleted file mode 100644 index eaddcdd7dd6..00000000000 --- a/eng/Analyzers.props +++ /dev/null @@ -1,11 +0,0 @@ - - - true - - false - - - - - - diff --git a/eng/Build.props b/eng/Build.props deleted file mode 100644 index ad50178c63b..00000000000 --- a/eng/Build.props +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/eng/SourceBuild.props b/eng/DotNetBuild.props similarity index 100% rename from eng/SourceBuild.props rename to eng/DotNetBuild.props diff --git a/eng/Package.props b/eng/Package.props deleted file mode 100644 index 85f63c6f07b..00000000000 --- a/eng/Package.props +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/eng/Publishing.props b/eng/Publishing.props index 579a1360d90..8b796225f82 100644 --- a/eng/Publishing.props +++ b/eng/Publishing.props @@ -1,7 +1,7 @@ - - - 3 - true - + + + true + + diff --git a/eng/SearchCache/InstallAzureCLI.sh b/eng/SearchCache/InstallAzureCLI.sh deleted file mode 100755 index 33f7d1c36c9..00000000000 --- a/eng/SearchCache/InstallAzureCLI.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env bash - -function retry { - local n=0 - local max=15 - local delay=60 - while true; do - ((n++)) - "$@" && { - echo "Command succeeded." - break - } || { - if [[ $n -lt $max ]]; then - echo "Command failed with the attempt $n/$max." - sleep $delay; - else - echo "The command has failed after $n attempts." - break - fi - } - done -} - -install_script="/tmp/azurecli_install.sh" -curl -sL https://aka.ms/InstallAzureCLIDeb -o "$install_script" -retry sudo bash "$install_script" diff --git a/eng/Signing.props b/eng/Signing.props index f233f020f21..065ce3d0870 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -1,4 +1,5 @@ + true @@ -18,4 +19,5 @@ + diff --git a/eng/SourceBuildPrebuiltBaseline.xml b/eng/SourceBuildPrebuiltBaseline.xml index 5e86a6ecc7e..854ceff4581 100644 --- a/eng/SourceBuildPrebuiltBaseline.xml +++ b/eng/SourceBuildPrebuiltBaseline.xml @@ -3,9 +3,5 @@ - - - - diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 22f69184b81..22f59001a56 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,31 +1,33 @@ - + + https://github.com/dotnet/source-build-externals - 3dc05150cf234f76f6936dcb2853d31a0da1f60e + 51b029e3272f35af0af337823cd122725f316c69 - + + https://github.com/dotnet/source-build-reference-packages - 6f814daa935e08b578b1c0c65a1f26ea3317f517 + 0d066e61a30c2599d0ced871ea45acf0e10571af - + https://github.com/dotnet/command-line-api - a045dd54a4c44723c215d992288160eb1401bb7f + 803d8598f98fb4efd94604b32627ee9407f246db - + https://github.com/dotnet/arcade - 1e2be7464703499cf98e20536fb4da4218c8fce1 - + 60ae233c3d77f11c5fdb53e570b64d503b13ba59 - - https://github.com/dotnet/xliff-tasks - 73f0850939d96131c28cf6ea6ee5aacb4da0083a - + + + https://github.com/dotnet/arcade + 60ae233c3d77f11c5fdb53e570b64d503b13ba59 + diff --git a/eng/Versions.props b/eng/Versions.props index 1e4b438053c..7ff97561080 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -1,25 +1,19 @@ - - - + - true - true - 8.0.402 + 9.0.100 - true + false release - true - preview + rc rtm servicing - - + 1 + true + true - - - - 2.0.0-beta4.23407.1 + + 2.0.0-beta4.24324.3 diff --git a/eng/common/SetupNugetSources.ps1 b/eng/common/SetupNugetSources.ps1 index efa2fd72bfa..2b0a5c9e665 100644 --- a/eng/common/SetupNugetSources.ps1 +++ b/eng/common/SetupNugetSources.ps1 @@ -1,17 +1,10 @@ -# This file is a temporary workaround for internal builds to be able to restore from private AzDO feeds. -# This file should be removed as part of this issue: https://github.com/dotnet/arcade/issues/4080 +# This script adds internal feeds required to build commits that depend on internal package sources. For instance, +# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables +# disabled internal Maestro (darc-int*) feeds. # -# What the script does is iterate over all package sources in the pointed NuGet.config and add a credential entry -# under for each Maestro managed private feed. Two additional credential -# entries are also added for the two private static internal feeds: dotnet3-internal and dotnet3-internal-transport. +# Optionally, this script also adds a credential entry for each of the internal feeds if supplied. # -# This script needs to be called in every job that will restore packages and which the base repo has -# private AzDO feeds in the NuGet.config. -# -# See example YAML call for this script below. Note the use of the variable `$(dn-bot-dnceng-artifact-feeds-rw)` -# from the AzureDevOps-Artifact-Feeds-Pats variable group. -# -# Any disabledPackageSources entries which start with "darc-int" will be re-enabled as part of this script executing +# See example call for this script below. # # - task: PowerShell@2 # displayName: Setup Private Feeds Credentials @@ -21,11 +14,18 @@ # arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token # env: # Token: $(dn-bot-dnceng-artifact-feeds-rw) +# +# Note that the NuGetAuthenticate task should be called after SetupNugetSources. +# This ensures that: +# - Appropriate creds are set for the added internal feeds (if not supplied to the scrupt) +# - The credential provider is installed. +# +# This logic is also abstracted into enable-internal-sources.yml. [CmdletBinding()] param ( [Parameter(Mandatory = $true)][string]$ConfigFile, - [Parameter(Mandatory = $true)][string]$Password + $Password ) $ErrorActionPreference = "Stop" @@ -48,11 +48,17 @@ function AddPackageSource($sources, $SourceName, $SourceEndPoint, $creds, $Usern else { Write-Host "Package source $SourceName already present." } + AddCredential -Creds $creds -Source $SourceName -Username $Username -pwd $pwd } # Add a credential node for the specified source function AddCredential($creds, $source, $username, $pwd) { + # If no cred supplied, don't do anything. + if (!$pwd) { + return; + } + # Looks for credential configuration for the given SourceName. Create it if none is found. $sourceElement = $creds.SelectSingleNode($Source) if ($sourceElement -eq $null) @@ -110,11 +116,6 @@ if (!(Test-Path $ConfigFile -PathType Leaf)) { ExitWithExitCode 1 } -if (!$Password) { - Write-PipelineTelemetryError -Category 'Build' -Message 'Eng/common/SetupNugetSources.ps1 returned a non-zero exit code. Please supply a valid PAT' - ExitWithExitCode 1 -} - # Load NuGet.config $doc = New-Object System.Xml.XmlDocument $filename = (Get-Item $ConfigFile).FullName @@ -127,11 +128,14 @@ if ($sources -eq $null) { $doc.DocumentElement.AppendChild($sources) | Out-Null } -# Looks for a node. Create it if none is found. -$creds = $doc.DocumentElement.SelectSingleNode("packageSourceCredentials") -if ($creds -eq $null) { - $creds = $doc.CreateElement("packageSourceCredentials") - $doc.DocumentElement.AppendChild($creds) | Out-Null +$creds = $null +if ($Password) { + # Looks for a node. Create it if none is found. + $creds = $doc.DocumentElement.SelectSingleNode("packageSourceCredentials") + if ($creds -eq $null) { + $creds = $doc.CreateElement("packageSourceCredentials") + $doc.DocumentElement.AppendChild($creds) | Out-Null + } } # Check for disabledPackageSources; we'll enable any darc-int ones we find there @@ -164,4 +168,4 @@ foreach ($dotnetVersion in $dotnetVersions) { } } -$doc.Save($filename) \ No newline at end of file +$doc.Save($filename) diff --git a/eng/common/SetupNugetSources.sh b/eng/common/SetupNugetSources.sh index d387c7eac95..b493479a1da 100644 --- a/eng/common/SetupNugetSources.sh +++ b/eng/common/SetupNugetSources.sh @@ -1,28 +1,27 @@ #!/usr/bin/env bash -# This file is a temporary workaround for internal builds to be able to restore from private AzDO feeds. -# This file should be removed as part of this issue: https://github.com/dotnet/arcade/issues/4080 +# This script adds internal feeds required to build commits that depend on internal package sources. For instance, +# dotnet6-internal would be added automatically if dotnet6 was found in the nuget.config file. In addition also enables +# disabled internal Maestro (darc-int*) feeds. +# +# Optionally, this script also adds a credential entry for each of the internal feeds if supplied. # -# What the script does is iterate over all package sources in the pointed NuGet.config and add a credential entry -# under for each Maestro's managed private feed. Two additional credential -# entries are also added for the two private static internal feeds: dotnet3-internal and dotnet3-internal-transport. -# -# This script needs to be called in every job that will restore packages and which the base repo has -# private AzDO feeds in the NuGet.config. -# -# See example YAML call for this script below. Note the use of the variable `$(dn-bot-dnceng-artifact-feeds-rw)` -# from the AzureDevOps-Artifact-Feeds-Pats variable group. -# -# Any disabledPackageSources entries which start with "darc-int" will be re-enabled as part of this script executing. +# See example call for this script below. # # - task: Bash@3 -# displayName: Setup Private Feeds Credentials +# displayName: Setup Internal Feeds # inputs: # filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh -# arguments: $(Build.SourcesDirectory)/NuGet.config $Token +# arguments: $(Build.SourcesDirectory)/NuGet.config # condition: ne(variables['Agent.OS'], 'Windows_NT') -# env: -# Token: $(dn-bot-dnceng-artifact-feeds-rw) +# - task: NuGetAuthenticate@1 +# +# Note that the NuGetAuthenticate task should be called after SetupNugetSources. +# This ensures that: +# - Appropriate creds are set for the added internal feeds (if not supplied to the scrupt) +# - The credential provider is installed. +# +# This logic is also abstracted into enable-internal-sources.yml. ConfigFile=$1 CredToken=$2 @@ -48,11 +47,6 @@ if [ ! -f "$ConfigFile" ]; then ExitWithExitCode 1 fi -if [ -z "$CredToken" ]; then - Write-PipelineTelemetryError -category 'Build' "Error: Eng/common/SetupNugetSources.sh returned a non-zero exit code. Please supply a valid PAT" - ExitWithExitCode 1 -fi - if [[ `uname -s` == "Darwin" ]]; then NL=$'\\\n' TB='' @@ -140,18 +134,20 @@ PackageSources+="$IFS" PackageSources+=$(grep -oh '"darc-int-[^"]*"' $ConfigFile | tr -d '"') IFS=$PrevIFS -for FeedName in ${PackageSources[@]} ; do - # Check if there is no existing credential for this FeedName - grep -i "<$FeedName>" $ConfigFile - if [ "$?" != "0" ]; then - echo "Adding credentials for $FeedName." +if [ "$CredToken" ]; then + for FeedName in ${PackageSources[@]} ; do + # Check if there is no existing credential for this FeedName + grep -i "<$FeedName>" $ConfigFile + if [ "$?" != "0" ]; then + echo "Adding credentials for $FeedName." - PackageSourceCredentialsNodeFooter="" - NewCredential="${TB}${TB}<$FeedName>${NL}${NL}${NL}" + PackageSourceCredentialsNodeFooter="" + NewCredential="${TB}${TB}<$FeedName>${NL}${NL}${NL}" - sed -i.bak "s|$PackageSourceCredentialsNodeFooter|$NewCredential${NL}$PackageSourceCredentialsNodeFooter|" $ConfigFile - fi -done + sed -i.bak "s|$PackageSourceCredentialsNodeFooter|$NewCredential${NL}$PackageSourceCredentialsNodeFooter|" $ConfigFile + fi + done +fi # Re-enable any entries in disabledPackageSources where the feed name contains darc-int grep -i "" $ConfigFile diff --git a/eng/common/build.cmd b/eng/common/build.cmd new file mode 100644 index 00000000000..99daf368aba --- /dev/null +++ b/eng/common/build.cmd @@ -0,0 +1,3 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0build.ps1""" %*" +exit /b %ErrorLevel% diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index 33a6f2d0e24..438f9920c43 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -19,6 +19,7 @@ Param( [switch] $pack, [switch] $publish, [switch] $clean, + [switch][Alias('pb')]$productBuild, [switch][Alias('bl')]$binaryLog, [switch][Alias('nobl')]$excludeCIBinarylog, [switch] $ci, @@ -58,6 +59,7 @@ function Print-Usage() { Write-Host " -sign Sign build outputs" Write-Host " -publish Publish artifacts (e.g. symbols)" Write-Host " -clean Clean the solution" + Write-Host " -productBuild Build the solution in the way it will be built in the full .NET product (VMR) build (short: -pb)" Write-Host "" Write-Host "Advanced settings:" @@ -120,6 +122,7 @@ function Build { /p:Deploy=$deploy ` /p:Test=$test ` /p:Pack=$pack ` + /p:DotNetBuildRepo=$productBuild ` /p:IntegrationTest=$integrationTest ` /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` diff --git a/eng/common/build.sh b/eng/common/build.sh index 50af40cdd2c..ac1ee8620cd 100755 --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -22,6 +22,9 @@ usage() echo " --sourceBuild Source-build the solution (short: -sb)" echo " Will additionally trigger the following actions: --restore, --build, --pack" echo " If --configuration is not set explicitly, will also set it to 'Release'" + echo " --productBuild Build the solution in the way it will be built in the full .NET product (VMR) build (short: -pb)" + echo " Will additionally trigger the following actions: --restore, --build, --pack" + echo " If --configuration is not set explicitly, will also set it to 'Release'" echo " --rebuild Rebuild solution" echo " --test Run all unit tests in the solution (short: -t)" echo " --integrationTest Run all integration tests in the solution" @@ -59,6 +62,7 @@ scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" restore=false build=false source_build=false +product_build=false rebuild=false test=false integration_test=false @@ -105,7 +109,7 @@ while [[ $# > 0 ]]; do -binarylog|-bl) binary_log=true ;; - -excludeCIBinarylog|-nobl) + -excludecibinarylog|-nobl) exclude_ci_binary_log=true ;; -pipelineslog|-pl) @@ -126,6 +130,13 @@ while [[ $# > 0 ]]; do -sourcebuild|-sb) build=true source_build=true + product_build=true + restore=true + pack=true + ;; + -productBuild|-pb) + build=true + product_build=true restore=true pack=true ;; @@ -219,7 +230,9 @@ function Build { /p:RepoRoot="$repo_root" \ /p:Restore=$restore \ /p:Build=$build \ + /p:DotNetBuildRepo=$product_build \ /p:ArcadeBuildFromSource=$source_build \ + /p:DotNetBuildSourceOnly=$source_build \ /p:Rebuild=$rebuild \ /p:Test=$test \ /p:Pack=$pack \ diff --git a/eng/common/core-templates/job/job.yml b/eng/common/core-templates/job/job.yml new file mode 100644 index 00000000000..c732bee9f4a --- /dev/null +++ b/eng/common/core-templates/job/job.yml @@ -0,0 +1,252 @@ +parameters: +# Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job + cancelTimeoutInMinutes: '' + condition: '' + container: '' + continueOnError: false + dependsOn: '' + displayName: '' + pool: '' + steps: [] + strategy: '' + timeoutInMinutes: '' + variables: [] + workspace: '' + templateContext: {} + +# Job base template specific parameters + # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md + # publishing defaults + artifacts: '' + enableMicrobuild: false + enablePublishBuildArtifacts: false + enablePublishBuildAssets: false + enablePublishTestResults: false + enablePublishUsingPipelines: false + enableBuildRetry: false + mergeTestResults: false + testRunTitle: '' + testResultsFormat: '' + name: '' + componentGovernanceSteps: [] + preSteps: [] + artifactPublishSteps: [] + runAsPublic: false + +# Sbom related params + enableSbom: true + PackageVersion: 9.0.0 + BuildDropPath: '$(Build.SourcesDirectory)/artifacts' + +# 1es specific parameters + is1ESPipeline: '' + +jobs: +- job: ${{ parameters.name }} + + ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: + cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} + + ${{ if ne(parameters.condition, '') }}: + condition: ${{ parameters.condition }} + + ${{ if ne(parameters.container, '') }}: + container: ${{ parameters.container }} + + ${{ if ne(parameters.continueOnError, '') }}: + continueOnError: ${{ parameters.continueOnError }} + + ${{ if ne(parameters.dependsOn, '') }}: + dependsOn: ${{ parameters.dependsOn }} + + ${{ if ne(parameters.displayName, '') }}: + displayName: ${{ parameters.displayName }} + + ${{ if ne(parameters.pool, '') }}: + pool: ${{ parameters.pool }} + + ${{ if ne(parameters.strategy, '') }}: + strategy: ${{ parameters.strategy }} + + ${{ if ne(parameters.timeoutInMinutes, '') }}: + timeoutInMinutes: ${{ parameters.timeoutInMinutes }} + + ${{ if ne(parameters.templateContext, '') }}: + templateContext: ${{ parameters.templateContext }} + + variables: + - ${{ if ne(parameters.enableTelemetry, 'false') }}: + - name: DOTNET_CLI_TELEMETRY_PROFILE + value: '$(Build.Repository.Uri)' + - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: + - name: EnableRichCodeNavigation + value: 'true' + # Retry signature validation up to three times, waiting 2 seconds between attempts. + # See https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu3028#retry-untrusted-root-failures + - name: NUGET_EXPERIMENTAL_CHAIN_BUILD_RETRY_POLICY + value: 3,2000 + - ${{ each variable in parameters.variables }}: + # handle name-value variable syntax + # example: + # - name: [key] + # value: [value] + - ${{ if ne(variable.name, '') }}: + - name: ${{ variable.name }} + value: ${{ variable.value }} + + # handle variable groups + - ${{ if ne(variable.group, '') }}: + - group: ${{ variable.group }} + + # handle template variable syntax + # example: + # - template: path/to/template.yml + # parameters: + # [key]: [value] + - ${{ if ne(variable.template, '') }}: + - template: ${{ variable.template }} + ${{ if ne(variable.parameters, '') }}: + parameters: ${{ variable.parameters }} + + # handle key-value variable syntax. + # example: + # - [key]: [value] + - ${{ if and(eq(variable.name, ''), eq(variable.group, ''), eq(variable.template, '')) }}: + - ${{ each pair in variable }}: + - name: ${{ pair.key }} + value: ${{ pair.value }} + + # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds + - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - group: DotNet-HelixApi-Access + + ${{ if ne(parameters.workspace, '') }}: + workspace: ${{ parameters.workspace }} + + steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ if ne(parameters.preSteps, '') }}: + - ${{ each preStep in parameters.preSteps }}: + - ${{ preStep }} + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - ${{ if eq(parameters.enableMicrobuild, 'true') }}: + - task: MicroBuildSigningPlugin@4 + displayName: Install MicroBuild plugin + inputs: + signType: $(_SignType) + zipSources: false + feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json + env: + TeamName: $(_TeamName) + MicroBuildOutputFolderOverride: '$(Agent.TempDirectory)' + continueOnError: ${{ parameters.continueOnError }} + condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) + + - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: + - task: NuGetAuthenticate@1 + + - ${{ if and(ne(parameters.artifacts.download, 'false'), ne(parameters.artifacts.download, '')) }}: + - task: DownloadPipelineArtifact@2 + inputs: + buildType: current + artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} + targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} + itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} + + - ${{ each step in parameters.steps }}: + - ${{ step }} + + - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: + - task: RichCodeNavIndexer@0 + displayName: RichCodeNav Upload + inputs: + languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} + environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'internal') }} + richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin + uploadRichNavArtifacts: ${{ coalesce(parameters.richCodeNavigationUploadArtifacts, false) }} + continueOnError: true + + - ${{ each step in parameters.componentGovernanceSteps }}: + - ${{ step }} + + - ${{ if eq(parameters.enableMicrobuild, 'true') }}: + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - task: MicroBuildCleanup@1 + displayName: Execute Microbuild cleanup tasks + condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) + continueOnError: ${{ parameters.continueOnError }} + env: + TeamName: $(_TeamName) + + # Publish test results + - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: + - task: PublishTestResults@2 + displayName: Publish XUnit Test Results + inputs: + testResultsFormat: 'xUnit' + testResultsFiles: '*.xml' + searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' + testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit + mergeTestResults: ${{ parameters.mergeTestResults }} + continueOnError: true + condition: always() + - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: + - task: PublishTestResults@2 + displayName: Publish TRX Test Results + inputs: + testResultsFormat: 'VSTest' + testResultsFiles: '*.trx' + searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' + testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx + mergeTestResults: ${{ parameters.mergeTestResults }} + continueOnError: true + condition: always() + + # gather artifacts + - ${{ if ne(parameters.artifacts.publish, '') }}: + - ${{ if and(ne(parameters.artifacts.publish.artifacts, 'false'), ne(parameters.artifacts.publish.artifacts, '')) }}: + - task: CopyFiles@2 + displayName: Gather binaries for publish to artifacts + inputs: + SourceFolder: 'artifacts/bin' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' + - task: CopyFiles@2 + displayName: Gather packages for publish to artifacts + inputs: + SourceFolder: 'artifacts/packages' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' + - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: + - task: CopyFiles@2 + displayName: Gather logs for publish to artifacts + inputs: + SourceFolder: 'artifacts/log' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/log' + continueOnError: true + condition: always() + + - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: + - task: CopyFiles@2 + displayName: Gather logs for publish to artifacts + inputs: + SourceFolder: 'artifacts/log/$(_BuildConfig)' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/log/$(_BuildConfig)' + continueOnError: true + condition: always() + - ${{ if eq(parameters.enableBuildRetry, 'true') }}: + - task: CopyFiles@2 + displayName: Gather buildconfiguration for build retry + inputs: + SourceFolder: '$(Build.SourcesDirectory)/eng/common/BuildConfiguration' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/eng/common/BuildConfiguration' + continueOnError: true + condition: always() + - ${{ each step in parameters.artifactPublishSteps }}: + - ${{ step }} diff --git a/eng/common/core-templates/job/onelocbuild.yml b/eng/common/core-templates/job/onelocbuild.yml new file mode 100644 index 00000000000..00feec8ebbc --- /dev/null +++ b/eng/common/core-templates/job/onelocbuild.yml @@ -0,0 +1,121 @@ +parameters: + # Optional: dependencies of the job + dependsOn: '' + + # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool + pool: '' + + CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex + GithubPat: $(BotAccount-dotnet-bot-repo-PAT) + + SourcesDirectory: $(Build.SourcesDirectory) + CreatePr: true + AutoCompletePr: false + ReusePr: true + UseLfLineEndings: true + UseCheckedInLocProjectJson: false + SkipLocProjectJsonGeneration: false + LanguageSet: VS_Main_Languages + LclSource: lclFilesInRepo + LclPackageId: '' + RepoType: gitHub + GitHubOrg: dotnet + MirrorRepo: '' + MirrorBranch: main + condition: '' + JobNameSuffix: '' + is1ESPipeline: '' +jobs: +- job: OneLocBuild${{ parameters.JobNameSuffix }} + + dependsOn: ${{ parameters.dependsOn }} + + displayName: OneLocBuild${{ parameters.JobNameSuffix }} + + variables: + - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat + - name: _GenerateLocProjectArguments + value: -SourcesDirectory ${{ parameters.SourcesDirectory }} + -LanguageSet "${{ parameters.LanguageSet }}" + -CreateNeutralXlfs + - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: + - name: _GenerateLocProjectArguments + value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson + - template: /eng/common/core-templates/variables/pool-providers.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + ${{ if ne(parameters.pool, '') }}: + pool: ${{ parameters.pool }} + ${{ if eq(parameters.pool, '') }}: + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + + steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ if ne(parameters.SkipLocProjectJsonGeneration, 'true') }}: + - task: Powershell@2 + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 + arguments: $(_GenerateLocProjectArguments) + displayName: Generate LocProject.json + condition: ${{ parameters.condition }} + + - task: OneLocBuild@2 + displayName: OneLocBuild + env: + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + inputs: + locProj: eng/Localize/LocProject.json + outDir: $(Build.ArtifactStagingDirectory) + lclSource: ${{ parameters.LclSource }} + lclPackageId: ${{ parameters.LclPackageId }} + isCreatePrSelected: ${{ parameters.CreatePr }} + isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} + ${{ if eq(parameters.CreatePr, true) }}: + isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} + ${{ if eq(parameters.RepoType, 'gitHub') }}: + isShouldReusePrSelected: ${{ parameters.ReusePr }} + packageSourceAuth: patAuth + patVariable: ${{ parameters.CeapexPat }} + ${{ if eq(parameters.RepoType, 'gitHub') }}: + repoType: ${{ parameters.RepoType }} + gitHubPatVariable: "${{ parameters.GithubPat }}" + ${{ if ne(parameters.MirrorRepo, '') }}: + isMirrorRepoSelected: true + gitHubOrganization: ${{ parameters.GitHubOrg }} + mirrorRepo: ${{ parameters.MirrorRepo }} + mirrorBranch: ${{ parameters.MirrorBranch }} + condition: ${{ parameters.condition }} + + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish Localization Files + pathToPublish: '$(Build.ArtifactStagingDirectory)/loc' + publishLocation: Container + artifactName: Loc + condition: ${{ parameters.condition }} + + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish LocProject.json + pathToPublish: '$(Build.SourcesDirectory)/eng/Localize/' + publishLocation: Container + artifactName: Loc + condition: ${{ parameters.condition }} \ No newline at end of file diff --git a/eng/common/core-templates/job/publish-build-assets.yml b/eng/common/core-templates/job/publish-build-assets.yml new file mode 100644 index 00000000000..3d3356e3196 --- /dev/null +++ b/eng/common/core-templates/job/publish-build-assets.yml @@ -0,0 +1,158 @@ +parameters: + configuration: 'Debug' + + # Optional: condition for the job to run + condition: '' + + # Optional: 'true' if future jobs should run even if this job fails + continueOnError: false + + # Optional: dependencies of the job + dependsOn: '' + + # Optional: Include PublishBuildArtifacts task + enablePublishBuildArtifacts: false + + # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool + pool: {} + + # Optional: should run as a public build even in the internal project + # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. + runAsPublic: false + + # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing + publishUsingPipelines: false + + # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing + publishAssetsImmediately: false + + artifactsPublishingAdditionalParameters: '' + + signingValidationAdditionalParameters: '' + + is1ESPipeline: '' + +jobs: +- job: Asset_Registry_Publish + + dependsOn: ${{ parameters.dependsOn }} + timeoutInMinutes: 150 + + ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: + displayName: Publish Assets + ${{ else }}: + displayName: Publish to Build Asset Registry + + variables: + - template: /eng/common/core-templates/variables/pool-providers.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - group: Publish-Build-Assets + - group: AzureDevOps-Artifact-Feeds-Pats + - name: runCodesignValidationInjection + value: false + # unconditional - needed for logs publishing (redactor tool version) + - template: /eng/common/core-templates/post-build/common-variables.yml + + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: + name: NetCore1ESPool-Publishing-Internal + image: windows.vs2019.amd64 + os: windows + steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - checkout: self + fetchDepth: 3 + clean: true + + - task: DownloadBuildArtifacts@0 + displayName: Download artifact + inputs: + artifactName: AssetManifests + downloadPath: '$(Build.StagingDirectory)/Download' + checkDownloadedFiles: true + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + + - task: NuGetAuthenticate@1 + + - task: AzureCLI@2 + displayName: Publish Build Assets + inputs: + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 + arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet + /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' + /p:MaestroApiEndpoint=https://maestro.dot.net + /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} + /p:OfficialBuildId=$(Build.BuildNumber) + condition: ${{ parameters.condition }} + continueOnError: ${{ parameters.continueOnError }} + + - task: powershell@2 + displayName: Create ReleaseConfigs Artifact + inputs: + targetType: inline + script: | + New-Item -Path "$(Build.StagingDirectory)/ReleaseConfigs" -ItemType Directory -Force + $filePath = "$(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt" + Add-Content -Path $filePath -Value $(BARBuildId) + Add-Content -Path $filePath -Value "$(DefaultChannels)" + Add-Content -Path $filePath -Value $(IsStableBuild) + + $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" + if (Test-Path -Path $symbolExclusionfile) + { + Write-Host "SymbolExclusionFile exists" + Copy-Item -Path $symbolExclusionfile -Destination "$(Build.StagingDirectory)/ReleaseConfigs" + } + + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish ReleaseConfigs Artifact + pathToPublish: '$(Build.StagingDirectory)/ReleaseConfigs' + publishLocation: Container + artifactName: ReleaseConfigs + + - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: + - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + BARBuildId: ${{ parameters.BARBuildId }} + PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + - task: AzureCLI@2 + displayName: Publish Using Darc + inputs: + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + arguments: > + -BuildId $(BARBuildId) + -PublishingInfraVersion 3 + -AzdoToken '$(System.AccessToken)' + -WaitPublishingFinish true + -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' + -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' + + - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: + - template: /eng/common/core-templates/steps/publish-logs.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + JobLabel: 'Publish_Artifacts_Logs' diff --git a/eng/common/core-templates/job/source-build.yml b/eng/common/core-templates/job/source-build.yml new file mode 100644 index 00000000000..c4713c8b6ed --- /dev/null +++ b/eng/common/core-templates/job/source-build.yml @@ -0,0 +1,93 @@ +parameters: + # This template adds arcade-powered source-build to CI. The template produces a server job with a + # default ID 'Source_Build_Complete' to put in a dependency list if necessary. + + # Specifies the prefix for source-build jobs added to pipeline. Use this if disambiguation needed. + jobNamePrefix: 'Source_Build' + + # Defines the platform on which to run the job. By default, a linux-x64 machine, suitable for + # managed-only repositories. This is an object with these properties: + # + # name: '' + # The name of the job. This is included in the job ID. + # targetRID: '' + # The name of the target RID to use, instead of the one auto-detected by Arcade. + # nonPortable: false + # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than + # linux-x64), and compiling against distro-provided packages rather than portable ones. + # skipPublishValidation: false + # Disables publishing validation. By default, a check is performed to ensure no packages are + # published by source-build. + # container: '' + # A container to use. Runs in docker. + # pool: {} + # A pool to use. Runs directly on an agent. + # buildScript: '' + # Specifies the build script to invoke to perform the build in the repo. The default + # './build.sh' should work for typical Arcade repositories, but this is customizable for + # difficult situations. + # jobProperties: {} + # A list of job properties to inject at the top level, for potential extensibility beyond + # container and pool. + platform: {} + + is1ESPipeline: '' + + # If set to true and running on a non-public project, + # Internal nuget and blob storage locations will be enabled. + # This is not enabled by default because many repositories do not need internal sources + # and do not need to have the required service connections approved in the pipeline. + enableInternalSources: false + +jobs: +- job: ${{ parameters.jobNamePrefix }}_${{ parameters.platform.name }} + displayName: Source-Build (${{ parameters.platform.name }}) + + ${{ each property in parameters.platform.jobProperties }}: + ${{ property.key }}: ${{ property.value }} + + ${{ if ne(parameters.platform.container, '') }}: + container: ${{ parameters.platform.container }} + + ${{ if eq(parameters.platform.pool, '') }}: + # The default VM host AzDO pool. This should be capable of running Docker containers: almost all + # source-build builds run in Docker, including the default managed platform. + # /eng/common/core-templates/variables/pool-providers.yml can't be used here (some customers declare variables already), so duplicate its logic + ${{ if eq(parameters.is1ESPipeline, 'true') }}: + pool: + ${{ if eq(variables['System.TeamProject'], 'public') }}: + name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore-Svc-Public' ), False, 'NetCore-Public')] + demands: ImageOverride -equals build.ubuntu.2004.amd64 + ${{ if eq(variables['System.TeamProject'], 'internal') }}: + name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore1ESPool-Svc-Internal'), False, 'NetCore1ESPool-Internal')] + image: 1es-mariner-2 + os: linux + ${{ else }}: + pool: + ${{ if eq(variables['System.TeamProject'], 'public') }}: + name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore-Svc-Public' ), False, 'NetCore-Public')] + demands: ImageOverride -equals Build.Ubuntu.2204.Amd64.Open + ${{ if eq(variables['System.TeamProject'], 'internal') }}: + name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore1ESPool-Svc-Internal'), False, 'NetCore1ESPool-Internal')] + demands: ImageOverride -equals Build.Ubuntu.2204.Amd64 + ${{ if ne(parameters.platform.pool, '') }}: + pool: ${{ parameters.platform.pool }} + + workspace: + clean: all + + steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ if eq(parameters.enableInternalSources, true) }}: + - template: /eng/common/core-templates/steps/enable-internal-sources.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + - template: /eng/common/core-templates/steps/enable-internal-runtimes.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + - template: /eng/common/core-templates/steps/source-build.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + platform: ${{ parameters.platform }} diff --git a/eng/common/core-templates/job/source-index-stage1.yml b/eng/common/core-templates/job/source-index-stage1.yml new file mode 100644 index 00000000000..205fb5b3a39 --- /dev/null +++ b/eng/common/core-templates/job/source-index-stage1.yml @@ -0,0 +1,81 @@ +parameters: + runAsPublic: false + sourceIndexUploadPackageVersion: 2.0.0-20240522.1 + sourceIndexProcessBinlogPackageVersion: 1.0.1-20240522.1 + sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json + sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" + preSteps: [] + binlogPath: artifacts/log/Debug/Build.binlog + condition: '' + dependsOn: '' + pool: '' + is1ESPipeline: '' + +jobs: +- job: SourceIndexStage1 + dependsOn: ${{ parameters.dependsOn }} + condition: ${{ parameters.condition }} + variables: + - name: SourceIndexUploadPackageVersion + value: ${{ parameters.sourceIndexUploadPackageVersion }} + - name: SourceIndexProcessBinlogPackageVersion + value: ${{ parameters.sourceIndexProcessBinlogPackageVersion }} + - name: SourceIndexPackageSource + value: ${{ parameters.sourceIndexPackageSource }} + - name: BinlogPath + value: ${{ parameters.binlogPath }} + - template: /eng/common/core-templates/variables/pool-providers.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + ${{ if ne(parameters.pool, '') }}: + pool: ${{ parameters.pool }} + ${{ if eq(parameters.pool, '') }}: + pool: + ${{ if eq(variables['System.TeamProject'], 'public') }}: + name: $(DncEngPublicBuildPool) + image: 1es-windows-2022-open + os: windows + ${{ if eq(variables['System.TeamProject'], 'internal') }}: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + + steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ each preStep in parameters.preSteps }}: + - ${{ preStep }} + + - task: UseDotNet@2 + displayName: Use .NET 8 SDK + inputs: + packageType: sdk + version: 8.0.x + installationPath: $(Agent.TempDirectory)/dotnet + workingDirectory: $(Agent.TempDirectory) + + - script: | + $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version $(sourceIndexProcessBinlogPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools + $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version $(sourceIndexUploadPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools + displayName: Download Tools + # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. + workingDirectory: $(Agent.TempDirectory) + + - script: ${{ parameters.sourceIndexBuildCommand }} + displayName: Build Repository + + - script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output + displayName: Process Binlog into indexable sln + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - task: AzureCLI@2 + displayName: Log in to Azure and upload stage1 artifacts to source index + inputs: + azureSubscription: 'SourceDotNet Stage1 Publish' + addSpnToEnvironment: true + scriptType: 'ps' + scriptLocation: 'inlineScript' + inlineScript: | + $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 diff --git a/eng/common/core-templates/jobs/codeql-build.yml b/eng/common/core-templates/jobs/codeql-build.yml new file mode 100644 index 00000000000..f2144252cc6 --- /dev/null +++ b/eng/common/core-templates/jobs/codeql-build.yml @@ -0,0 +1,33 @@ +parameters: + # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md + continueOnError: false + # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job + jobs: [] + # Optional: if specified, restore and use this version of Guardian instead of the default. + overrideGuardianVersion: '' + is1ESPipeline: '' + +jobs: +- template: /eng/common/core-templates/jobs/jobs.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + enableMicrobuild: false + enablePublishBuildArtifacts: false + enablePublishTestResults: false + enablePublishBuildAssets: false + enablePublishUsingPipelines: false + enableTelemetry: true + + variables: + - group: Publish-Build-Assets + # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in + # sync with the packages.config file. + - name: DefaultGuardianVersion + value: 0.109.0 + - name: GuardianPackagesConfigFile + value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config + - name: GuardianVersion + value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} + + jobs: ${{ parameters.jobs }} + diff --git a/eng/common/core-templates/jobs/jobs.yml b/eng/common/core-templates/jobs/jobs.yml new file mode 100644 index 00000000000..ea69be4341c --- /dev/null +++ b/eng/common/core-templates/jobs/jobs.yml @@ -0,0 +1,119 @@ +parameters: + # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md + continueOnError: false + + # Optional: Include PublishBuildArtifacts task + enablePublishBuildArtifacts: false + + # Optional: Enable publishing using release pipelines + enablePublishUsingPipelines: false + + # Optional: Enable running the source-build jobs to build repo from source + enableSourceBuild: false + + # Optional: Parameters for source-build template. + # See /eng/common/core-templates/jobs/source-build.yml for options + sourceBuildParameters: [] + + graphFileGeneration: + # Optional: Enable generating the graph files at the end of the build + enabled: false + # Optional: Include toolset dependencies in the generated graph files + includeToolset: false + + # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job + jobs: [] + + # Optional: Override automatically derived dependsOn value for "publish build assets" job + publishBuildAssetsDependsOn: '' + + # Optional: Publish the assets as soon as the publish to BAR stage is complete, rather doing so in a separate stage. + publishAssetsImmediately: false + + # Optional: If using publishAssetsImmediately and additional parameters are needed, can be used to send along additional parameters (normally sent to post-build.yml) + artifactsPublishingAdditionalParameters: '' + signingValidationAdditionalParameters: '' + + # Optional: should run as a public build even in the internal project + # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. + runAsPublic: false + + enableSourceIndex: false + sourceIndexParams: {} + + artifacts: {} + is1ESPipeline: '' + +# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, +# and some (Microbuild) should only be applied to non-PR cases for internal builds. + +jobs: +- ${{ each job in parameters.jobs }}: + - ${{ if eq(parameters.is1ESPipeline, 'true') }}: + - template: /eng/common/templates-official/job/job.yml + parameters: + # pass along parameters + ${{ each parameter in parameters }}: + ${{ if ne(parameter.key, 'jobs') }}: + ${{ parameter.key }}: ${{ parameter.value }} + + # pass along job properties + ${{ each property in job }}: + ${{ if ne(property.key, 'job') }}: + ${{ property.key }}: ${{ property.value }} + + name: ${{ job.job }} + + - ${{ else }}: + - template: /eng/common/templates/job/job.yml + parameters: + # pass along parameters + ${{ each parameter in parameters }}: + ${{ if ne(parameter.key, 'jobs') }}: + ${{ parameter.key }}: ${{ parameter.value }} + + # pass along job properties + ${{ each property in job }}: + ${{ if ne(property.key, 'job') }}: + ${{ property.key }}: ${{ property.value }} + + name: ${{ job.job }} + +- ${{ if eq(parameters.enableSourceBuild, true) }}: + - template: /eng/common/core-templates/jobs/source-build.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + allCompletedJobId: Source_Build_Complete + ${{ each parameter in parameters.sourceBuildParameters }}: + ${{ parameter.key }}: ${{ parameter.value }} + +- ${{ if eq(parameters.enableSourceIndex, 'true') }}: + - template: ../job/source-index-stage1.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + runAsPublic: ${{ parameters.runAsPublic }} + ${{ each parameter in parameters.sourceIndexParams }}: + ${{ parameter.key }}: ${{ parameter.value }} + +- ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - ${{ if or(eq(parameters.enablePublishBuildAssets, true), eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: + - template: ../job/publish-build-assets.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + continueOnError: ${{ parameters.continueOnError }} + dependsOn: + - ${{ if ne(parameters.publishBuildAssetsDependsOn, '') }}: + - ${{ each job in parameters.publishBuildAssetsDependsOn }}: + - ${{ job.job }} + - ${{ if eq(parameters.publishBuildAssetsDependsOn, '') }}: + - ${{ each job in parameters.jobs }}: + - ${{ job.job }} + - ${{ if eq(parameters.enableSourceBuild, true) }}: + - Source_Build_Complete + + runAsPublic: ${{ parameters.runAsPublic }} + publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} + publishAssetsImmediately: ${{ parameters.publishAssetsImmediately }} + enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} + artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} + signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} diff --git a/eng/common/core-templates/jobs/source-build.yml b/eng/common/core-templates/jobs/source-build.yml new file mode 100644 index 00000000000..a10ccfbee6d --- /dev/null +++ b/eng/common/core-templates/jobs/source-build.yml @@ -0,0 +1,58 @@ +parameters: + # This template adds arcade-powered source-build to CI. A job is created for each platform, as + # well as an optional server job that completes when all platform jobs complete. + + # The name of the "join" job for all source-build platforms. If set to empty string, the job is + # not included. Existing repo pipelines can use this job depend on all source-build jobs + # completing without maintaining a separate list of every single job ID: just depend on this one + # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. + allCompletedJobId: '' + + # See /eng/common/core-templates/job/source-build.yml + jobNamePrefix: 'Source_Build' + + # This is the default platform provided by Arcade, intended for use by a managed-only repo. + defaultManagedPlatform: + name: 'Managed' + container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream9' + + # Defines the platforms on which to run build jobs. One job is created for each platform, and the + # object in this array is sent to the job template as 'platform'. If no platforms are specified, + # one job runs on 'defaultManagedPlatform'. + platforms: [] + + is1ESPipeline: '' + + # If set to true and running on a non-public project, + # Internal nuget and blob storage locations will be enabled. + # This is not enabled by default because many repositories do not need internal sources + # and do not need to have the required service connections approved in the pipeline. + enableInternalSources: false + +jobs: + +- ${{ if ne(parameters.allCompletedJobId, '') }}: + - job: ${{ parameters.allCompletedJobId }} + displayName: Source-Build Complete + pool: server + dependsOn: + - ${{ each platform in parameters.platforms }}: + - ${{ parameters.jobNamePrefix }}_${{ platform.name }} + - ${{ if eq(length(parameters.platforms), 0) }}: + - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} + +- ${{ each platform in parameters.platforms }}: + - template: /eng/common/core-templates/job/source-build.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + jobNamePrefix: ${{ parameters.jobNamePrefix }} + platform: ${{ platform }} + enableInternalSources: ${{ parameters.enableInternalSources }} + +- ${{ if eq(length(parameters.platforms), 0) }}: + - template: /eng/common/core-templates/job/source-build.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + jobNamePrefix: ${{ parameters.jobNamePrefix }} + platform: ${{ parameters.defaultManagedPlatform }} + enableInternalSources: ${{ parameters.enableInternalSources }} diff --git a/eng/common/core-templates/post-build/common-variables.yml b/eng/common/core-templates/post-build/common-variables.yml new file mode 100644 index 00000000000..d5627a994ae --- /dev/null +++ b/eng/common/core-templates/post-build/common-variables.yml @@ -0,0 +1,22 @@ +variables: + - group: Publish-Build-Assets + + # Whether the build is internal or not + - name: IsInternalBuild + value: ${{ and(ne(variables['System.TeamProject'], 'public'), contains(variables['Build.SourceBranch'], 'internal')) }} + + # Default Maestro++ API Endpoint and API Version + - name: MaestroApiEndPoint + value: "https://maestro.dot.net" + - name: MaestroApiVersion + value: "2020-02-20" + + - name: SourceLinkCLIVersion + value: 3.0.0 + - name: SymbolToolVersion + value: 1.0.1 + - name: BinlogToolVersion + value: 1.0.11 + + - name: runCodesignValidationInjection + value: false diff --git a/eng/common/core-templates/post-build/post-build.yml b/eng/common/core-templates/post-build/post-build.yml new file mode 100644 index 00000000000..454fd75c7af --- /dev/null +++ b/eng/common/core-templates/post-build/post-build.yml @@ -0,0 +1,316 @@ +parameters: + # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST. + # Publishing V1 is no longer supported + # Publishing V2 is no longer supported + # Publishing V3 is the default + - name: publishingInfraVersion + displayName: Which version of publishing should be used to promote the build definition? + type: number + default: 3 + values: + - 3 + + - name: BARBuildId + displayName: BAR Build Id + type: number + default: 0 + + - name: PromoteToChannelIds + displayName: Channel to promote BARBuildId to + type: string + default: '' + + - name: enableSourceLinkValidation + displayName: Enable SourceLink validation + type: boolean + default: false + + - name: enableSigningValidation + displayName: Enable signing validation + type: boolean + default: true + + - name: enableSymbolValidation + displayName: Enable symbol validation + type: boolean + default: false + + - name: enableNugetValidation + displayName: Enable NuGet validation + type: boolean + default: true + + - name: publishInstallersAndChecksums + displayName: Publish installers and checksums + type: boolean + default: true + + - name: SDLValidationParameters + type: object + default: + enable: false + publishGdn: false + continueOnError: false + params: '' + artifactNames: '' + downloadArtifacts: true + + # These parameters let the user customize the call to sdk-task.ps1 for publishing + # symbols & general artifacts as well as for signing validation + - name: symbolPublishingAdditionalParameters + displayName: Symbol publishing additional parameters + type: string + default: '' + + - name: artifactsPublishingAdditionalParameters + displayName: Artifact publishing additional parameters + type: string + default: '' + + - name: signingValidationAdditionalParameters + displayName: Signing validation additional parameters + type: string + default: '' + + # Which stages should finish execution before post-build stages start + - name: validateDependsOn + type: object + default: + - build + + - name: publishDependsOn + type: object + default: + - Validate + + # Optional: Call asset publishing rather than running in a separate stage + - name: publishAssetsImmediately + type: boolean + default: false + + - name: is1ESPipeline + type: boolean + default: false + +stages: +- ${{ if or(eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: + - stage: Validate + dependsOn: ${{ parameters.validateDependsOn }} + displayName: Validate Build Assets + variables: + - template: /eng/common/core-templates/post-build/common-variables.yml + - template: /eng/common/core-templates/variables/pool-providers.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + jobs: + - job: + displayName: NuGet Validation + condition: and(succeededOrFailed(), eq( ${{ parameters.enableNugetValidation }}, 'true')) + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ else }}: + ${{ if eq(parameters.is1ESPipeline, true) }}: + name: $(DncEngInternalBuildPool) + image: windows.vs2022.amd64 + os: windows + ${{ else }}: + name: $(DncEngInternalBuildPool) + demands: ImageOverride -equals windows.vs2022.amd64 + + steps: + - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + BARBuildId: ${{ parameters.BARBuildId }} + PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + - task: DownloadBuildArtifacts@0 + displayName: Download Package Artifacts + inputs: + buildType: specific + buildVersionToDownload: specific + project: $(AzDOProjectName) + pipeline: $(AzDOPipelineId) + buildId: $(AzDOBuildId) + artifactName: PackageArtifacts + checkDownloadedFiles: true + + - task: PowerShell@2 + displayName: Validate + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/post-build/nuget-validation.ps1 + arguments: -PackagesPath $(Build.ArtifactStagingDirectory)/PackageArtifacts/ + + - job: + displayName: Signing Validation + condition: and( eq( ${{ parameters.enableSigningValidation }}, 'true'), ne( variables['PostBuildSign'], 'true')) + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ else }}: + ${{ if eq(parameters.is1ESPipeline, true) }}: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + ${{ else }}: + name: $(DncEngInternalBuildPool) + demands: ImageOverride -equals windows.vs2022.amd64 + steps: + - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + BARBuildId: ${{ parameters.BARBuildId }} + PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + - task: DownloadBuildArtifacts@0 + displayName: Download Package Artifacts + inputs: + buildType: specific + buildVersionToDownload: specific + project: $(AzDOProjectName) + pipeline: $(AzDOPipelineId) + buildId: $(AzDOBuildId) + artifactName: PackageArtifacts + checkDownloadedFiles: true + itemPattern: | + ** + !**/Microsoft.SourceBuild.Intermediate.*.nupkg + + # This is necessary whenever we want to publish/restore to an AzDO private feed + # Since sdk-task.ps1 tries to restore packages we need to do this authentication here + # otherwise it'll complain about accessing a private feed. + - task: NuGetAuthenticate@1 + displayName: 'Authenticate to AzDO Feeds' + + # Signing validation will optionally work with the buildmanifest file which is downloaded from + # Azure DevOps above. + - task: PowerShell@2 + displayName: Validate + inputs: + filePath: eng\common\sdk-task.ps1 + arguments: -task SigningValidation -restore -msbuildEngine vs + /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts' + /p:SignCheckExclusionsFile='$(Build.SourcesDirectory)/eng/SignCheckExclusionsFile.txt' + ${{ parameters.signingValidationAdditionalParameters }} + + - template: /eng/common/core-templates/steps/publish-logs.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + StageLabel: 'Validation' + JobLabel: 'Signing' + BinlogToolVersion: $(BinlogToolVersion) + + - job: + displayName: SourceLink Validation + condition: eq( ${{ parameters.enableSourceLinkValidation }}, 'true') + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ else }}: + ${{ if eq(parameters.is1ESPipeline, true) }}: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + ${{ else }}: + name: $(DncEngInternalBuildPool) + demands: ImageOverride -equals windows.vs2022.amd64 + steps: + - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + BARBuildId: ${{ parameters.BARBuildId }} + PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + - task: DownloadBuildArtifacts@0 + displayName: Download Blob Artifacts + inputs: + buildType: specific + buildVersionToDownload: specific + project: $(AzDOProjectName) + pipeline: $(AzDOPipelineId) + buildId: $(AzDOBuildId) + artifactName: BlobArtifacts + checkDownloadedFiles: true + + - task: PowerShell@2 + displayName: Validate + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/post-build/sourcelink-validation.ps1 + arguments: -InputPath $(Build.ArtifactStagingDirectory)/BlobArtifacts/ + -ExtractPath $(Agent.BuildDirectory)/Extract/ + -GHRepoName $(Build.Repository.Name) + -GHCommit $(Build.SourceVersion) + -SourcelinkCliVersion $(SourceLinkCLIVersion) + continueOnError: true + +- ${{ if ne(parameters.publishAssetsImmediately, 'true') }}: + - stage: publish_using_darc + ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: + dependsOn: ${{ parameters.publishDependsOn }} + ${{ else }}: + dependsOn: ${{ parameters.validateDependsOn }} + displayName: Publish using Darc + variables: + - template: /eng/common/core-templates/post-build/common-variables.yml + - template: /eng/common/core-templates/variables/pool-providers.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + jobs: + - job: + displayName: Publish Using Darc + timeoutInMinutes: 120 + pool: + # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) + ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: + name: AzurePipelines-EO + image: 1ESPT-Windows2022 + demands: Cmd + os: windows + # If it's not devdiv, it's dnceng + ${{ else }}: + ${{ if eq(parameters.is1ESPipeline, true) }}: + name: NetCore1ESPool-Publishing-Internal + image: windows.vs2019.amd64 + os: windows + ${{ else }}: + name: NetCore1ESPool-Publishing-Internal + demands: ImageOverride -equals windows.vs2019.amd64 + steps: + - template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + BARBuildId: ${{ parameters.BARBuildId }} + PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} + is1ESPipeline: ${{ parameters.is1ESPipeline }} + + - task: NuGetAuthenticate@1 + + - task: AzureCLI@2 + displayName: Publish Using Darc + inputs: + azureSubscription: "Darc: Maestro Production" + scriptType: ps + scriptLocation: scriptPath + scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + arguments: > + -BuildId $(BARBuildId) + -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} + -AzdoToken '$(System.AccessToken)' + -WaitPublishingFinish true + -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' + -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' diff --git a/eng/common/core-templates/post-build/setup-maestro-vars.yml b/eng/common/core-templates/post-build/setup-maestro-vars.yml new file mode 100644 index 00000000000..f7602980dbe --- /dev/null +++ b/eng/common/core-templates/post-build/setup-maestro-vars.yml @@ -0,0 +1,74 @@ +parameters: + BARBuildId: '' + PromoteToChannelIds: '' + is1ESPipeline: '' + +steps: + - ${{ if eq(parameters.is1ESPipeline, '') }}: + - 'Illegal entry point, is1ESPipeline is not defined. Repository yaml should not directly reference templates in core-templates folder.': error + + - ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}: + - task: DownloadBuildArtifacts@0 + displayName: Download Release Configs + inputs: + buildType: current + artifactName: ReleaseConfigs + checkDownloadedFiles: true + + - task: AzureCLI@2 + name: setReleaseVars + displayName: Set Release Configs Vars + inputs: + azureSubscription: "Darc: Maestro Production" + scriptType: pscore + scriptLocation: inlineScript + inlineScript: | + try { + if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { + $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt + + $BarId = $Content | Select -Index 0 + $Channels = $Content | Select -Index 1 + $IsStableBuild = $Content | Select -Index 2 + + $AzureDevOpsProject = $Env:System_TeamProject + $AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId + $AzureDevOpsBuildId = $Env:Build_BuildId + } + else { + . $(Build.SourcesDirectory)\eng\common\tools.ps1 + $darc = Get-Darc + $buildInfo = & $darc get-build ` + --id ${{ parameters.BARBuildId }} ` + --extended ` + --output-format json ` + --ci ` + | convertFrom-Json + + $BarId = ${{ parameters.BARBuildId }} + $Channels = $Env:PromoteToMaestroChannels -split "," + $Channels = $Channels -join "][" + $Channels = "[$Channels]" + + $IsStableBuild = $buildInfo.stable + $AzureDevOpsProject = $buildInfo.azureDevOpsProject + $AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId + $AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId + } + + Write-Host "##vso[task.setvariable variable=BARBuildId]$BarId" + Write-Host "##vso[task.setvariable variable=TargetChannels]$Channels" + Write-Host "##vso[task.setvariable variable=IsStableBuild]$IsStableBuild" + + Write-Host "##vso[task.setvariable variable=AzDOProjectName]$AzureDevOpsProject" + Write-Host "##vso[task.setvariable variable=AzDOPipelineId]$AzureDevOpsBuildDefinitionId" + Write-Host "##vso[task.setvariable variable=AzDOBuildId]$AzureDevOpsBuildId" + } + catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + exit 1 + } + env: + PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }} diff --git a/eng/common/core-templates/steps/component-governance.yml b/eng/common/core-templates/steps/component-governance.yml new file mode 100644 index 00000000000..cf0649aa956 --- /dev/null +++ b/eng/common/core-templates/steps/component-governance.yml @@ -0,0 +1,16 @@ +parameters: + disableComponentGovernance: false + componentGovernanceIgnoreDirectories: '' + is1ESPipeline: false + displayName: 'Component Detection' + +steps: +- ${{ if eq(parameters.disableComponentGovernance, 'true') }}: + - script: echo "##vso[task.setvariable variable=skipComponentGovernanceDetection]true" + displayName: Set skipComponentGovernanceDetection variable +- ${{ if ne(parameters.disableComponentGovernance, 'true') }}: + - task: ComponentGovernanceComponentDetection@0 + continueOnError: true + displayName: ${{ parameters.displayName }} + inputs: + ignoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} diff --git a/eng/common/core-templates/steps/enable-internal-runtimes.yml b/eng/common/core-templates/steps/enable-internal-runtimes.yml new file mode 100644 index 00000000000..6bdbf62ac50 --- /dev/null +++ b/eng/common/core-templates/steps/enable-internal-runtimes.yml @@ -0,0 +1,32 @@ +# Obtains internal runtime download credentials and populates the 'dotnetbuilds-internal-container-read-token-base64' +# variable with the base64-encoded SAS token, by default + +parameters: +- name: federatedServiceConnection + type: string + default: 'dotnetbuilds-internal-read' +- name: outputVariableName + type: string + default: 'dotnetbuilds-internal-container-read-token-base64' +- name: expiryInHours + type: number + default: 1 +- name: base64Encode + type: boolean + default: true +- name: is1ESPipeline + type: boolean + default: false + +steps: +- ${{ if ne(variables['System.TeamProject'], 'public') }}: + - template: /eng/common/core-templates/steps/get-delegation-sas.yml + parameters: + federatedServiceConnection: ${{ parameters.federatedServiceConnection }} + outputVariableName: ${{ parameters.outputVariableName }} + expiryInHours: ${{ parameters.expiryInHours }} + base64Encode: ${{ parameters.base64Encode }} + storageAccount: dotnetbuilds + container: internal + permissions: rl + is1ESPipeline: ${{ parameters.is1ESPipeline }} \ No newline at end of file diff --git a/eng/common/core-templates/steps/enable-internal-sources.yml b/eng/common/core-templates/steps/enable-internal-sources.yml new file mode 100644 index 00000000000..64f881bffc3 --- /dev/null +++ b/eng/common/core-templates/steps/enable-internal-sources.yml @@ -0,0 +1,47 @@ +parameters: +# This is the Azure federated service connection that we log into to get an access token. +- name: nugetFederatedServiceConnection + type: string + default: 'dnceng-artifacts-feeds-read' +- name: is1ESPipeline + type: boolean + default: false +# Legacy parameters to allow for PAT usage +- name: legacyCredential + type: string + default: '' + +steps: +- ${{ if ne(variables['System.TeamProject'], 'public') }}: + - ${{ if ne(parameters.legacyCredential, '') }}: + - task: PowerShell@2 + displayName: Setup Internal Feeds + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token + env: + Token: ${{ parameters.legacyCredential }} + # If running on dnceng (internal project), just use the default behavior for NuGetAuthenticate. + # If running on DevDiv, NuGetAuthenticate is not really an option. It's scoped to a single feed, and we have many feeds that + # may be added. Instead, we'll use the traditional approach (add cred to nuget.config), but use an account token. + - ${{ else }}: + - ${{ if eq(variables['System.TeamProject'], 'internal') }}: + - task: PowerShell@2 + displayName: Setup Internal Feeds + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config + - ${{ else }}: + - template: /eng/common/templates/steps/get-federated-access-token.yml + parameters: + federatedServiceConnection: ${{ parameters.nugetFederatedServiceConnection }} + outputVariableName: 'dnceng-artifacts-feeds-read-access-token' + - task: PowerShell@2 + displayName: Setup Internal Feeds + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1 + arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $(dnceng-artifacts-feeds-read-access-token) + # This is required in certain scenarios to install the ADO credential provider. + # It installed by default in some msbuild invocations (e.g. VS msbuild), but needs to be installed for others + # (e.g. dotnet msbuild). + - task: NuGetAuthenticate@1 diff --git a/eng/common/core-templates/steps/generate-sbom.yml b/eng/common/core-templates/steps/generate-sbom.yml new file mode 100644 index 00000000000..d938b60e1bb --- /dev/null +++ b/eng/common/core-templates/steps/generate-sbom.yml @@ -0,0 +1,54 @@ +# BuildDropPath - The root folder of the drop directory for which the manifest file will be generated. +# PackageName - The name of the package this SBOM represents. +# PackageVersion - The version of the package this SBOM represents. +# ManifestDirPath - The path of the directory where the generated manifest files will be placed +# IgnoreDirectories - Directories to ignore for SBOM generation. This will be passed through to the CG component detector. + +parameters: + PackageVersion: 9.0.0 + BuildDropPath: '$(Build.SourcesDirectory)/artifacts' + PackageName: '.NET' + ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom + IgnoreDirectories: '' + sbomContinueOnError: true + is1ESPipeline: false + # disable publishArtifacts if some other step is publishing the artifacts (like job.yml). + publishArtifacts: true + +steps: +- task: PowerShell@2 + displayName: Prep for SBOM generation in (Non-linux) + condition: or(eq(variables['Agent.Os'], 'Windows_NT'), eq(variables['Agent.Os'], 'Darwin')) + inputs: + filePath: ./eng/common/generate-sbom-prep.ps1 + arguments: ${{parameters.manifestDirPath}} + +# Chmodding is a workaround for https://github.com/dotnet/arcade/issues/8461 +- script: | + chmod +x ./eng/common/generate-sbom-prep.sh + ./eng/common/generate-sbom-prep.sh ${{parameters.manifestDirPath}} + displayName: Prep for SBOM generation in (Linux) + condition: eq(variables['Agent.Os'], 'Linux') + continueOnError: ${{ parameters.sbomContinueOnError }} + +- task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 + displayName: 'Generate SBOM manifest' + continueOnError: ${{ parameters.sbomContinueOnError }} + inputs: + PackageName: ${{ parameters.packageName }} + BuildDropPath: ${{ parameters.buildDropPath }} + PackageVersion: ${{ parameters.packageVersion }} + ManifestDirPath: ${{ parameters.manifestDirPath }} + ${{ if ne(parameters.IgnoreDirectories, '') }}: + AdditionalComponentDetectorArgs: '--IgnoreDirectories ${{ parameters.IgnoreDirectories }}' + +- ${{ if eq(parameters.publishArtifacts, 'true')}}: + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish SBOM manifest + continueOnError: ${{parameters.sbomContinueOnError}} + targetPath: '${{ parameters.manifestDirPath }}' + artifactName: $(ARTIFACT_NAME) + diff --git a/eng/common/core-templates/steps/get-delegation-sas.yml b/eng/common/core-templates/steps/get-delegation-sas.yml new file mode 100644 index 00000000000..d2901470a7f --- /dev/null +++ b/eng/common/core-templates/steps/get-delegation-sas.yml @@ -0,0 +1,46 @@ +parameters: +- name: federatedServiceConnection + type: string +- name: outputVariableName + type: string +- name: expiryInHours + type: number + default: 1 +- name: base64Encode + type: boolean + default: false +- name: storageAccount + type: string +- name: container + type: string +- name: permissions + type: string + default: 'rl' +- name: is1ESPipeline + type: boolean + default: false + +steps: +- task: AzureCLI@2 + displayName: 'Generate delegation SAS Token for ${{ parameters.storageAccount }}/${{ parameters.container }}' + inputs: + azureSubscription: ${{ parameters.federatedServiceConnection }} + scriptType: 'pscore' + scriptLocation: 'inlineScript' + inlineScript: | + # Calculate the expiration of the SAS token and convert to UTC + $expiry = (Get-Date).AddHours(${{ parameters.expiryInHours }}).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") + + $sas = az storage container generate-sas --account-name ${{ parameters.storageAccount }} --name ${{ parameters.container }} --permissions ${{ parameters.permissions }} --expiry $expiry --auth-mode login --as-user -o tsv + + if ($LASTEXITCODE -ne 0) { + Write-Error "Failed to generate SAS token." + exit 1 + } + + if ('${{ parameters.base64Encode }}' -eq 'true') { + $sas = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sas)) + } + + Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" + Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true]$sas" diff --git a/eng/common/core-templates/steps/get-federated-access-token.yml b/eng/common/core-templates/steps/get-federated-access-token.yml new file mode 100644 index 00000000000..3a4d4410c48 --- /dev/null +++ b/eng/common/core-templates/steps/get-federated-access-token.yml @@ -0,0 +1,42 @@ +parameters: +- name: federatedServiceConnection + type: string +- name: outputVariableName + type: string +- name: is1ESPipeline + type: boolean +- name: stepName + type: string + default: 'getFederatedAccessToken' +- name: condition + type: string + default: '' +# Resource to get a token for. Common values include: +# - '499b84ac-1321-427f-aa17-267ca6975798' for Azure DevOps +# - 'https://storage.azure.com/' for storage +# Defaults to Azure DevOps +- name: resource + type: string + default: '499b84ac-1321-427f-aa17-267ca6975798' +- name: isStepOutputVariable + type: boolean + default: false + +steps: +- task: AzureCLI@2 + displayName: 'Getting federated access token for feeds' + name: ${{ parameters.stepName }} + ${{ if ne(parameters.condition, '') }}: + condition: ${{ parameters.condition }} + inputs: + azureSubscription: ${{ parameters.federatedServiceConnection }} + scriptType: 'pscore' + scriptLocation: 'inlineScript' + inlineScript: | + $accessToken = az account get-access-token --query accessToken --resource ${{ parameters.resource }} --output tsv + if ($LASTEXITCODE -ne 0) { + Write-Error "Failed to get access token for resource '${{ parameters.resource }}'" + exit 1 + } + Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" + Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" \ No newline at end of file diff --git a/eng/common/core-templates/steps/publish-build-artifacts.yml b/eng/common/core-templates/steps/publish-build-artifacts.yml new file mode 100644 index 00000000000..f24ce346684 --- /dev/null +++ b/eng/common/core-templates/steps/publish-build-artifacts.yml @@ -0,0 +1,20 @@ +parameters: +- name: is1ESPipeline + type: boolean + default: false +- name: args + type: object + default: {} +steps: +- ${{ if ne(parameters.is1ESPipeline, true) }}: + - template: /eng/common/templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + ${{ each parameter in parameters.args }}: + ${{ parameter.key }}: ${{ parameter.value }} +- ${{ else }}: + - template: /eng/common/templates-official/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + ${{ each parameter in parameters.args }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/core-templates/steps/publish-logs.yml b/eng/common/core-templates/steps/publish-logs.yml new file mode 100644 index 00000000000..80788c52319 --- /dev/null +++ b/eng/common/core-templates/steps/publish-logs.yml @@ -0,0 +1,58 @@ +parameters: + StageLabel: '' + JobLabel: '' + CustomSensitiveDataList: '' + # A default - in case value from eng/common/core-templates/post-build/common-variables.yml is not passed + BinlogToolVersion: '1.0.11' + is1ESPipeline: false + +steps: +- task: Powershell@2 + displayName: Prepare Binlogs to Upload + inputs: + targetType: inline + script: | + New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ + Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ + continueOnError: true + condition: always() + +- task: PowerShell@2 + displayName: Redact Logs + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/post-build/redact-logs.ps1 + # For now this needs to have explicit list of all sensitive data. Taken from eng/publishing/v3/publish.yml + # Sensitive data can as well be added to $(Build.SourcesDirectory)/eng/BinlogSecretsRedactionFile.txt' + # If the file exists - sensitive data for redaction will be sourced from it + # (single entry per line, lines starting with '# ' are considered comments and skipped) + arguments: -InputPath '$(Build.SourcesDirectory)/PostBuildLogs' + -BinlogToolVersion ${{parameters.BinlogToolVersion}} + -TokensFilePath '$(Build.SourcesDirectory)/eng/BinlogSecretsRedactionFile.txt' + '$(publishing-dnceng-devdiv-code-r-build-re)' + '$(MaestroAccessToken)' + '$(dn-bot-all-orgs-artifact-feeds-rw)' + '$(akams-client-id)' + '$(microsoft-symbol-server-pat)' + '$(symweb-symbol-server-pat)' + '$(dn-bot-all-orgs-build-rw-code-rw)' + ${{parameters.CustomSensitiveDataList}} + continueOnError: true + condition: always() + +- task: CopyFiles@2 + displayName: Gather post build logs + inputs: + SourceFolder: '$(Build.SourcesDirectory)/PostBuildLogs' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/PostBuildLogs' + +- template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish Logs + pathToPublish: '$(Build.ArtifactStagingDirectory)/PostBuildLogs' + publishLocation: Container + artifactName: PostBuildLogs + continueOnError: true + condition: always() diff --git a/eng/common/core-templates/steps/publish-pipeline-artifacts.yml b/eng/common/core-templates/steps/publish-pipeline-artifacts.yml new file mode 100644 index 00000000000..2efec04dc2c --- /dev/null +++ b/eng/common/core-templates/steps/publish-pipeline-artifacts.yml @@ -0,0 +1,20 @@ +parameters: +- name: is1ESPipeline + type: boolean + default: false + +- name: args + type: object + default: {} + +steps: +- ${{ if ne(parameters.is1ESPipeline, true) }}: + - template: /eng/common/templates/steps/publish-pipeline-artifacts.yml + parameters: + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} +- ${{ else }}: + - template: /eng/common/templates-official/steps/publish-pipeline-artifacts.yml + parameters: + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/core-templates/steps/retain-build.yml b/eng/common/core-templates/steps/retain-build.yml new file mode 100644 index 00000000000..83d97a26a01 --- /dev/null +++ b/eng/common/core-templates/steps/retain-build.yml @@ -0,0 +1,28 @@ +parameters: + # Optional azure devops PAT with build execute permissions for the build's organization, + # only needed if the build that should be retained ran on a different organization than + # the pipeline where this template is executing from + Token: '' + # Optional BuildId to retain, defaults to the current running build + BuildId: '' + # Azure devops Organization URI for the build in the https://dev.azure.com/ format. + # Defaults to the organization the current pipeline is running on + AzdoOrgUri: '$(System.CollectionUri)' + # Azure devops project for the build. Defaults to the project the current pipeline is running on + AzdoProject: '$(System.TeamProject)' + +steps: + - task: powershell@2 + inputs: + targetType: 'filePath' + filePath: eng/common/retain-build.ps1 + pwsh: true + arguments: > + -AzdoOrgUri: ${{parameters.AzdoOrgUri}} + -AzdoProject ${{parameters.AzdoProject}} + -Token ${{coalesce(parameters.Token, '$env:SYSTEM_ACCESSTOKEN') }} + -BuildId ${{coalesce(parameters.BuildId, '$env:BUILD_ID')}} + displayName: Enable permanent build retention + env: + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + BUILD_ID: $(Build.BuildId) \ No newline at end of file diff --git a/eng/common/core-templates/steps/send-to-helix.yml b/eng/common/core-templates/steps/send-to-helix.yml new file mode 100644 index 00000000000..68fa739c4ab --- /dev/null +++ b/eng/common/core-templates/steps/send-to-helix.yml @@ -0,0 +1,93 @@ +# Please remember to update the documentation if you make changes to these parameters! +parameters: + HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ + HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' + HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number + HelixTargetQueues: '' # required -- semicolon-delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues + HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group + HelixProjectPath: 'eng/common/helixpublish.proj' # optional -- path to the project file to build relative to BUILD_SOURCESDIRECTORY + HelixProjectArguments: '' # optional -- arguments passed to the build command + HelixConfiguration: '' # optional -- additional property attached to a job + HelixPreCommands: '' # optional -- commands to run before Helix work item execution + HelixPostCommands: '' # optional -- commands to run after Helix work item execution + WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects + WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects + WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects + CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload + XUnitProjects: '' # optional -- semicolon-delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true + XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects + XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects + XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner + XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects + IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion + DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json + DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json + WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." + IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set + HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting https://helix.int-dot.net ) + Creator: '' # optional -- if the build is external, use this to specify who is sending the job + DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO + condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() + continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false + +steps: + - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY/${{ parameters.HelixProjectPath }} /restore /p:TreatWarningsAsErrors=false ${{ parameters.HelixProjectArguments }} /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' + displayName: ${{ parameters.DisplayNamePrefix }} (Windows) + env: + BuildConfig: $(_BuildConfig) + HelixSource: ${{ parameters.HelixSource }} + HelixType: ${{ parameters.HelixType }} + HelixBuild: ${{ parameters.HelixBuild }} + HelixConfiguration: ${{ parameters.HelixConfiguration }} + HelixTargetQueues: ${{ parameters.HelixTargetQueues }} + HelixAccessToken: ${{ parameters.HelixAccessToken }} + HelixPreCommands: ${{ parameters.HelixPreCommands }} + HelixPostCommands: ${{ parameters.HelixPostCommands }} + WorkItemDirectory: ${{ parameters.WorkItemDirectory }} + WorkItemCommand: ${{ parameters.WorkItemCommand }} + WorkItemTimeout: ${{ parameters.WorkItemTimeout }} + CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} + XUnitProjects: ${{ parameters.XUnitProjects }} + XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} + XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} + XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} + XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} + IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} + DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} + DotNetCliVersion: ${{ parameters.DotNetCliVersion }} + WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} + HelixBaseUri: ${{ parameters.HelixBaseUri }} + Creator: ${{ parameters.Creator }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) + continueOnError: ${{ parameters.continueOnError }} + - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/${{ parameters.HelixProjectPath }} /restore /p:TreatWarningsAsErrors=false ${{ parameters.HelixProjectArguments }} /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog + displayName: ${{ parameters.DisplayNamePrefix }} (Unix) + env: + BuildConfig: $(_BuildConfig) + HelixSource: ${{ parameters.HelixSource }} + HelixType: ${{ parameters.HelixType }} + HelixBuild: ${{ parameters.HelixBuild }} + HelixConfiguration: ${{ parameters.HelixConfiguration }} + HelixTargetQueues: ${{ parameters.HelixTargetQueues }} + HelixAccessToken: ${{ parameters.HelixAccessToken }} + HelixPreCommands: ${{ parameters.HelixPreCommands }} + HelixPostCommands: ${{ parameters.HelixPostCommands }} + WorkItemDirectory: ${{ parameters.WorkItemDirectory }} + WorkItemCommand: ${{ parameters.WorkItemCommand }} + WorkItemTimeout: ${{ parameters.WorkItemTimeout }} + CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} + XUnitProjects: ${{ parameters.XUnitProjects }} + XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} + XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} + XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} + XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} + IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} + DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} + DotNetCliVersion: ${{ parameters.DotNetCliVersion }} + WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} + HelixBaseUri: ${{ parameters.HelixBaseUri }} + Creator: ${{ parameters.Creator }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) + condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) + continueOnError: ${{ parameters.continueOnError }} diff --git a/eng/common/core-templates/steps/source-build.yml b/eng/common/core-templates/steps/source-build.yml new file mode 100644 index 00000000000..2915d29bb7f --- /dev/null +++ b/eng/common/core-templates/steps/source-build.yml @@ -0,0 +1,129 @@ +parameters: + # This template adds arcade-powered source-build to CI. + + # This is a 'steps' template, and is intended for advanced scenarios where the existing build + # infra has a careful build methodology that must be followed. For example, a repo + # (dotnet/runtime) might choose to clone the GitHub repo only once and store it as a pipeline + # artifact for all subsequent jobs to use, to reduce dependence on a strong network connection to + # GitHub. Using this steps template leaves room for that infra to be included. + + # Defines the platform on which to run the steps. See 'eng/common/core-templates/job/source-build.yml' + # for details. The entire object is described in the 'job' template for simplicity, even though + # the usage of the properties on this object is split between the 'job' and 'steps' templates. + platform: {} + is1ESPipeline: false + +steps: +# Build. Keep it self-contained for simple reusability. (No source-build-specific job variables.) +- script: | + set -x + df -h + + # If file changes are detected, set CopyWipIntoInnerSourceBuildRepo to copy the WIP changes into the inner source build repo. + internalRestoreArgs= + if ! git diff --quiet; then + internalRestoreArgs='/p:CopyWipIntoInnerSourceBuildRepo=true' + # The 'Copy WIP' feature of source build uses git stash to apply changes from the original repo. + # This only works if there is a username/email configured, which won't be the case in most CI runs. + git config --get user.email + if [ $? -ne 0 ]; then + git config user.email dn-bot@microsoft.com + git config user.name dn-bot + fi + fi + + # If building on the internal project, the internal storage variable may be available (usually only if needed) + # In that case, add variables to allow the download of internal runtimes if the specified versions are not found + # in the default public locations. + internalRuntimeDownloadArgs= + if [ '$(dotnetbuilds-internal-container-read-token-base64)' != '$''(dotnetbuilds-internal-container-read-token-base64)' ]; then + internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://dotnetbuilds.blob.core.windows.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://dotnetbuilds.blob.core.windows.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' + fi + + buildConfig=Release + # Check if AzDO substitutes in a build config from a variable, and use it if so. + if [ '$(_BuildConfig)' != '$''(_BuildConfig)' ]; then + buildConfig='$(_BuildConfig)' + fi + + officialBuildArgs= + if [ '${{ and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}' = 'True' ]; then + officialBuildArgs='/p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER)' + fi + + targetRidArgs= + if [ '${{ parameters.platform.targetRID }}' != '' ]; then + targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' + fi + + runtimeOsArgs= + if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then + runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}' + fi + + baseOsArgs= + if [ '${{ parameters.platform.baseOS }}' != '' ]; then + baseOsArgs='/p:BaseOS=${{ parameters.platform.baseOS }}' + fi + + publishArgs= + if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then + publishArgs='--publish' + fi + + assetManifestFileName=SourceBuild_RidSpecific.xml + if [ '${{ parameters.platform.name }}' != '' ]; then + assetManifestFileName=SourceBuild_${{ parameters.platform.name }}.xml + fi + + ${{ coalesce(parameters.platform.buildScript, './build.sh') }} --ci \ + --configuration $buildConfig \ + --restore --build --pack $publishArgs -bl \ + $officialBuildArgs \ + $internalRuntimeDownloadArgs \ + $internalRestoreArgs \ + $targetRidArgs \ + $runtimeOsArgs \ + $baseOsArgs \ + /p:SourceBuildNonPortable=${{ parameters.platform.nonPortable }} \ + /p:ArcadeBuildFromSource=true \ + /p:DotNetBuildSourceOnly=true \ + /p:DotNetBuildRepo=true \ + /p:AssetManifestFileName=$assetManifestFileName + displayName: Build + +# Upload build logs for diagnosis. +- task: CopyFiles@2 + displayName: Prepare BuildLogs staging directory + inputs: + SourceFolder: '$(Build.SourcesDirectory)' + Contents: | + **/*.log + **/*.binlog + artifacts/sb/prebuilt-report/** + TargetFolder: '$(Build.StagingDirectory)/BuildLogs' + CleanTargetFolder: true + continueOnError: true + condition: succeededOrFailed() + +- template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: ${{ parameters.is1ESPipeline }} + args: + displayName: Publish BuildLogs + targetPath: '$(Build.StagingDirectory)/BuildLogs' + artifactName: BuildLogs_SourceBuild_${{ parameters.platform.name }}_Attempt$(System.JobAttempt) + continueOnError: true + condition: succeededOrFailed() + sbomEnabled: false # we don't need SBOM for logs + +# Manually inject component detection so that we can ignore the source build upstream cache, which contains +# a nupkg cache of input packages (a local feed). +# This path must match the upstream cache path in property 'CurrentRepoSourceBuiltNupkgCacheDir' +# in src\Microsoft.DotNet.Arcade.Sdk\tools\SourceBuild\SourceBuildArcade.targets +- template: /eng/common/core-templates/steps/component-governance.yml + parameters: + displayName: Component Detection (Exclude upstream cache) + is1ESPipeline: ${{ parameters.is1ESPipeline }} + componentGovernanceIgnoreDirectories: '$(Build.SourcesDirectory)/artifacts/sb/src/artifacts/obj/source-built-upstream-cache' + disableComponentGovernance: ${{ eq(variables['System.TeamProject'], 'public') }} diff --git a/eng/common/core-templates/variables/pool-providers.yml b/eng/common/core-templates/variables/pool-providers.yml new file mode 100644 index 00000000000..41053d382a2 --- /dev/null +++ b/eng/common/core-templates/variables/pool-providers.yml @@ -0,0 +1,8 @@ +parameters: + is1ESPipeline: false + +variables: + - ${{ if eq(parameters.is1ESPipeline, 'true') }}: + - template: /eng/common/templates-official/variables/pool-providers.yml + - ${{ else }}: + - template: /eng/common/templates/variables/pool-providers.yml \ No newline at end of file diff --git a/eng/common/cross/arm/sources.list.bionic b/eng/common/cross/arm/sources.list.bionic deleted file mode 100644 index 21095574095..00000000000 --- a/eng/common/cross/arm/sources.list.bionic +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.focal b/eng/common/cross/arm/sources.list.focal deleted file mode 100644 index 4de2600c174..00000000000 --- a/eng/common/cross/arm/sources.list.focal +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.jammy b/eng/common/cross/arm/sources.list.jammy deleted file mode 100644 index 6bb0453029c..00000000000 --- a/eng/common/cross/arm/sources.list.jammy +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.jessie b/eng/common/cross/arm/sources.list.jessie deleted file mode 100644 index 4d142ac9b10..00000000000 --- a/eng/common/cross/arm/sources.list.jessie +++ /dev/null @@ -1,3 +0,0 @@ -# Debian (sid) # UNSTABLE -deb http://ftp.debian.org/debian/ sid main contrib non-free -deb-src http://ftp.debian.org/debian/ sid main contrib non-free diff --git a/eng/common/cross/arm/sources.list.xenial b/eng/common/cross/arm/sources.list.xenial deleted file mode 100644 index 56fbb36a59f..00000000000 --- a/eng/common/cross/arm/sources.list.xenial +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.zesty b/eng/common/cross/arm/sources.list.zesty deleted file mode 100644 index ea2c14a7874..00000000000 --- a/eng/common/cross/arm/sources.list.zesty +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.bionic b/eng/common/cross/arm64/sources.list.bionic deleted file mode 100644 index 21095574095..00000000000 --- a/eng/common/cross/arm64/sources.list.bionic +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.buster b/eng/common/cross/arm64/sources.list.buster deleted file mode 100644 index 7194ac64a96..00000000000 --- a/eng/common/cross/arm64/sources.list.buster +++ /dev/null @@ -1,11 +0,0 @@ -deb http://deb.debian.org/debian buster main -deb-src http://deb.debian.org/debian buster main - -deb http://deb.debian.org/debian-security/ buster/updates main -deb-src http://deb.debian.org/debian-security/ buster/updates main - -deb http://deb.debian.org/debian buster-updates main -deb-src http://deb.debian.org/debian buster-updates main - -deb http://deb.debian.org/debian buster-backports main contrib non-free -deb-src http://deb.debian.org/debian buster-backports main contrib non-free diff --git a/eng/common/cross/arm64/sources.list.focal b/eng/common/cross/arm64/sources.list.focal deleted file mode 100644 index 4de2600c174..00000000000 --- a/eng/common/cross/arm64/sources.list.focal +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.jammy b/eng/common/cross/arm64/sources.list.jammy deleted file mode 100644 index 6bb0453029c..00000000000 --- a/eng/common/cross/arm64/sources.list.jammy +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.stretch b/eng/common/cross/arm64/sources.list.stretch deleted file mode 100644 index 0e121577436..00000000000 --- a/eng/common/cross/arm64/sources.list.stretch +++ /dev/null @@ -1,12 +0,0 @@ -deb http://deb.debian.org/debian stretch main -deb-src http://deb.debian.org/debian stretch main - -deb http://deb.debian.org/debian-security/ stretch/updates main -deb-src http://deb.debian.org/debian-security/ stretch/updates main - -deb http://deb.debian.org/debian stretch-updates main -deb-src http://deb.debian.org/debian stretch-updates main - -deb http://deb.debian.org/debian stretch-backports main contrib non-free -deb-src http://deb.debian.org/debian stretch-backports main contrib non-free - diff --git a/eng/common/cross/arm64/sources.list.xenial b/eng/common/cross/arm64/sources.list.xenial deleted file mode 100644 index 56fbb36a59f..00000000000 --- a/eng/common/cross/arm64/sources.list.xenial +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ xenial-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.zesty b/eng/common/cross/arm64/sources.list.zesty deleted file mode 100644 index ea2c14a7874..00000000000 --- a/eng/common/cross/arm64/sources.list.zesty +++ /dev/null @@ -1,11 +0,0 @@ -deb http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-updates main restricted universe - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-backports main restricted - -deb http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse -deb-src http://ports.ubuntu.com/ubuntu-ports/ zesty-security main restricted universe multiverse diff --git a/eng/common/cross/armel/sources.list.jessie b/eng/common/cross/armel/sources.list.jessie deleted file mode 100644 index 3d9c3059d89..00000000000 --- a/eng/common/cross/armel/sources.list.jessie +++ /dev/null @@ -1,3 +0,0 @@ -# Debian (jessie) # Stable -deb http://ftp.debian.org/debian/ jessie main contrib non-free -deb-src http://ftp.debian.org/debian/ jessie main contrib non-free diff --git a/eng/common/cross/armv6/sources.list.buster b/eng/common/cross/armv6/sources.list.buster deleted file mode 100644 index f27fc4fb346..00000000000 --- a/eng/common/cross/armv6/sources.list.buster +++ /dev/null @@ -1,2 +0,0 @@ -deb http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi -deb-src http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi diff --git a/eng/common/cross/build-android-rootfs.sh b/eng/common/cross/build-android-rootfs.sh index f163fb9dae9..7e9ba2b75ed 100755 --- a/eng/common/cross/build-android-rootfs.sh +++ b/eng/common/cross/build-android-rootfs.sh @@ -5,15 +5,15 @@ __NDK_Version=r21 usage() { echo "Creates a toolchain and sysroot used for cross-compiling for Android." - echo. + echo echo "Usage: $0 [BuildArch] [ApiLevel]" - echo. + echo echo "BuildArch is the target architecture of Android. Currently only arm64 is supported." echo "ApiLevel is the target Android API level. API levels usually match to Android releases. See https://source.android.com/source/build-numbers.html" - echo. + echo echo "By default, the toolchain and sysroot will be generated in cross/android-rootfs/toolchain/[BuildArch]. You can change this behavior" echo "by setting the TOOLCHAIN_DIR environment variable" - echo. + echo echo "By default, the NDK will be downloaded into the cross/android-rootfs/android-ndk-$__NDK_Version directory. If you already have an NDK installation," echo "you can set the NDK_DIR environment variable to have this script use that installation of the NDK." echo "By default, this script will generate a file, android_platform, in the root of the ROOTFS_DIR directory that contains the RID for the supported and tested Android build: android.28-arm64. This file is to replace '/etc/os-release', which is not available for Android." diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 9caf9b021db..4b5e8d7166b 100755 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -8,7 +8,7 @@ usage() echo "BuildArch can be: arm(default), arm64, armel, armv6, ppc64le, riscv64, s390x, x64, x86" echo "CodeName - optional, Code name for Linux, can be: xenial(default), zesty, bionic, alpine" echo " for alpine can be specified with version: alpineX.YY or alpineedge" - echo " for FreeBSD can be: freebsd12, freebsd13" + echo " for FreeBSD can be: freebsd13, freebsd14" echo " for illumos can be: illumos" echo " for Haiku can be: haiku." echo "lldbx.y - optional, LLDB version, can be: lldb3.9(default), lldb4.0, lldb5.0, lldb6.0 no-lldb. Ignored for alpine and FreeBSD" @@ -30,7 +30,8 @@ __IllumosArch=arm7 __HaikuArch=arm __QEMUArch=arm __UbuntuArch=armhf -__UbuntuRepo="http://ports.ubuntu.com/" +__UbuntuRepo= +__UbuntuSuites="updates security backports" __LLDB_Package="liblldb-3.9-dev" __SkipUnmount=0 @@ -71,9 +72,9 @@ __AlpinePackages+=" krb5-dev" __AlpinePackages+=" openssl-dev" __AlpinePackages+=" zlib-dev" -__FreeBSDBase="12.4-RELEASE" +__FreeBSDBase="13.3-RELEASE" __FreeBSDPkg="1.17.0" -__FreeBSDABI="12" +__FreeBSDABI="13" __FreeBSDPackages="libunwind" __FreeBSDPackages+=" icu" __FreeBSDPackages+=" libinotify" @@ -129,6 +130,7 @@ __AlpineKeys=' 616db30d:MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnpUpyWDWjlUk3smlWeA0\nlIMW+oJ38t92CRLHH3IqRhyECBRW0d0aRGtq7TY8PmxjjvBZrxTNDpJT6KUk4LRm\na6A6IuAI7QnNK8SJqM0DLzlpygd7GJf8ZL9SoHSH+gFsYF67Cpooz/YDqWrlN7Vw\ntO00s0B+eXy+PCXYU7VSfuWFGK8TGEv6HfGMALLjhqMManyvfp8hz3ubN1rK3c8C\nUS/ilRh1qckdbtPvoDPhSbTDmfU1g/EfRSIEXBrIMLg9ka/XB9PvWRrekrppnQzP\nhP9YE3x/wbFc5QqQWiRCYyQl/rgIMOXvIxhkfe8H5n1Et4VAorkpEAXdsfN8KSVv\nLSMazVlLp9GYq5SUpqYX3KnxdWBgN7BJoZ4sltsTpHQ/34SXWfu3UmyUveWj7wp0\nx9hwsPirVI00EEea9AbP7NM2rAyu6ukcm4m6ATd2DZJIViq2es6m60AE6SMCmrQF\nwmk4H/kdQgeAELVfGOm2VyJ3z69fQuywz7xu27S6zTKi05Qlnohxol4wVb6OB7qG\nLPRtK9ObgzRo/OPumyXqlzAi/Yvyd1ZQk8labZps3e16bQp8+pVPiumWioMFJDWV\nGZjCmyMSU8V6MB6njbgLHoyg2LCukCAeSjbPGGGYhnKLm1AKSoJh3IpZuqcKCk5C\n8CM1S15HxV78s9dFntEqIokCAwEAAQ== ' __Keyring= +__KeyringFile="/usr/share/keyrings/ubuntu-archive-keyring.gpg" __SkipSigCheck=0 __UseMirror=0 @@ -142,7 +144,6 @@ while :; do case $lowerI in -\?|-h|--help) usage - exit 1 ;; arm) __BuildArch=arm @@ -163,6 +164,7 @@ while :; do __UbuntuArch=armel __UbuntuRepo="http://ftp.debian.org/debian/" __CodeName=jessie + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" ;; armv6) __BuildArch=armv6 @@ -170,10 +172,12 @@ while :; do __QEMUArch=arm __UbuntuRepo="http://raspbian.raspberrypi.org/raspbian/" __CodeName=buster + __KeyringFile="/usr/share/keyrings/raspbian-archive-keyring.gpg" __LLDB_Package="liblldb-6.0-dev" + __UbuntuSuites= - if [[ -e "/usr/share/keyrings/raspbian-archive-keyring.gpg" ]]; then - __Keyring="--keyring /usr/share/keyrings/raspbian-archive-keyring.gpg" + if [[ -e "$__KeyringFile" ]]; then + __Keyring="--keyring $__KeyringFile" fi ;; riscv64) @@ -182,13 +186,8 @@ while :; do __AlpinePackages="${__AlpinePackages// lldb-dev/}" __QEMUArch=riscv64 __UbuntuArch=riscv64 - __UbuntuRepo="http://deb.debian.org/debian-ports" __UbuntuPackages="${__UbuntuPackages// libunwind8-dev/}" unset __LLDB_Package - - if [[ -e "/usr/share/keyrings/debian-ports-archive-keyring.gpg" ]]; then - __Keyring="--keyring /usr/share/keyrings/debian-ports-archive-keyring.gpg --include=debian-ports-archive-keyring" - fi ;; ppc64le) __BuildArch=ppc64le @@ -229,12 +228,19 @@ while :; do __UbuntuRepo="http://archive.ubuntu.com/ubuntu/" ;; lldb*) - version="${lowerI/lldb/}" - parts=(${version//./ }) + version="$(echo "$lowerI" | tr -d '[:alpha:]-=')" + majorVersion="${version%%.*}" + + [ -z "${version##*.*}" ] && minorVersion="${version#*.}" + if [ -z "$minorVersion" ]; then + minorVersion=0 + fi # for versions > 6.0, lldb has dropped the minor version - if [[ "${parts[0]}" -gt 6 ]]; then - version="${parts[0]}" + if [ "$majorVersion" -le 6 ]; then + version="$majorVersion.$minorVersion" + else + version="$majorVersion" fi __LLDB_Package="liblldb-${version}-dev" @@ -243,15 +249,19 @@ while :; do unset __LLDB_Package ;; llvm*) - version="${lowerI/llvm/}" - parts=(${version//./ }) - __LLVM_MajorVersion="${parts[0]}" - __LLVM_MinorVersion="${parts[1]}" - - # for versions > 6.0, llvm has dropped the minor version - if [[ -z "$__LLVM_MinorVersion" && "$__LLVM_MajorVersion" -le 6 ]]; then - __LLVM_MinorVersion=0; + version="$(echo "$lowerI" | tr -d '[:alpha:]-=')" + __LLVM_MajorVersion="${version%%.*}" + + [ -z "${version##*.*}" ] && __LLVM_MinorVersion="${version#*.}" + if [ -z "$__LLVM_MinorVersion" ]; then + __LLVM_MinorVersion=0 + fi + + # for versions > 6.0, lldb has dropped the minor version + if [ "$__LLVM_MajorVersion" -gt 6 ]; then + __LLVM_MinorVersion= fi + ;; xenial) # Ubuntu 16.04 if [[ "$__CodeName" != "jessie" ]]; then @@ -278,8 +288,17 @@ while :; do __CodeName=jammy fi ;; + noble) # Ubuntu 24.04 + if [[ "$__CodeName" != "jessie" ]]; then + __CodeName=noble + fi + if [[ -n "$__LLDB_Package" ]]; then + __LLDB_Package="liblldb-18-dev" + fi + ;; jessie) # Debian 8 __CodeName=jessie + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -288,6 +307,7 @@ while :; do stretch) # Debian 9 __CodeName=stretch __LLDB_Package="liblldb-6.0-dev" + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -296,6 +316,7 @@ while :; do buster) # Debian 10 __CodeName=buster __LLDB_Package="liblldb-6.0-dev" + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -303,6 +324,15 @@ while :; do ;; bullseye) # Debian 11 __CodeName=bullseye + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" + + if [[ -z "$__UbuntuRepo" ]]; then + __UbuntuRepo="http://ftp.debian.org/debian/" + fi + ;; + bookworm) # Debian 12 + __CodeName=bookworm + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -310,6 +340,7 @@ while :; do ;; sid) # Debian sid __CodeName=sid + __KeyringFile="/usr/share/keyrings/debian-archive-keyring.gpg" if [[ -z "$__UbuntuRepo" ]]; then __UbuntuRepo="http://ftp.debian.org/debian/" @@ -323,25 +354,24 @@ while :; do alpine*) __CodeName=alpine __UbuntuRepo= - version="${lowerI/alpine/}" - if [[ "$version" == "edge" ]]; then + if [[ "$lowerI" == "alpineedge" ]]; then __AlpineVersion=edge else - parts=(${version//./ }) - __AlpineMajorVersion="${parts[0]}" - __AlpineMinoVersion="${parts[1]}" - __AlpineVersion="$__AlpineMajorVersion.$__AlpineMinoVersion" + version="$(echo "$lowerI" | tr -d '[:alpha:]-=')" + __AlpineMajorVersion="${version%%.*}" + __AlpineMinorVersion="${version#*.}" + __AlpineVersion="$__AlpineMajorVersion.$__AlpineMinorVersion" fi ;; - freebsd12) + freebsd13) __CodeName=freebsd __SkipUnmount=1 ;; - freebsd13) + freebsd14) __CodeName=freebsd - __FreeBSDBase="13.2-RELEASE" - __FreeBSDABI="13" + __FreeBSDBase="14.0-RELEASE" + __FreeBSDABI="14" __SkipUnmount=1 ;; illumos) @@ -420,6 +450,10 @@ fi __UbuntuPackages+=" ${__LLDB_Package:-}" +if [[ -z "$__UbuntuRepo" ]]; then + __UbuntuRepo="http://ports.ubuntu.com/" +fi + if [[ -n "$__LLVM_MajorVersion" ]]; then __UbuntuPackages+=" libclang-common-${__LLVM_MajorVersion}${__LLVM_MinorVersion:+.$__LLVM_MinorVersion}-dev" fi @@ -442,13 +476,39 @@ fi mkdir -p "$__RootfsDir" __RootfsDir="$( cd "$__RootfsDir" && pwd )" +__hasWget= +ensureDownloadTool() +{ + if command -v wget &> /dev/null; then + __hasWget=1 + elif command -v curl &> /dev/null; then + __hasWget=0 + else + >&2 echo "ERROR: either wget or curl is required by this script." + exit 1 + fi +} + if [[ "$__CodeName" == "alpine" ]]; then __ApkToolsVersion=2.12.11 - __ApkToolsSHA512SUM=53e57b49230da07ef44ee0765b9592580308c407a8d4da7125550957bb72cb59638e04f8892a18b584451c8d841d1c7cb0f0ab680cc323a3015776affaa3be33 __ApkToolsDir="$(mktemp -d)" __ApkKeysDir="$(mktemp -d)" + arch="$(uname -m)" - wget "https://gitlab.alpinelinux.org/api/v4/projects/5/packages/generic//v$__ApkToolsVersion/x86_64/apk.static" -P "$__ApkToolsDir" + ensureDownloadTool + + if [[ "$__hasWget" == 1 ]]; then + wget -P "$__ApkToolsDir" "https://gitlab.alpinelinux.org/api/v4/projects/5/packages/generic/v$__ApkToolsVersion/$arch/apk.static" + else + curl -SLO --create-dirs --output-dir "$__ApkToolsDir" "https://gitlab.alpinelinux.org/api/v4/projects/5/packages/generic/v$__ApkToolsVersion/$arch/apk.static" + fi + if [[ "$arch" == "x86_64" ]]; then + __ApkToolsSHA512SUM="53e57b49230da07ef44ee0765b9592580308c407a8d4da7125550957bb72cb59638e04f8892a18b584451c8d841d1c7cb0f0ab680cc323a3015776affaa3be33" + elif [[ "$arch" == "aarch64" ]]; then + __ApkToolsSHA512SUM="9e2b37ecb2b56c05dad23d379be84fd494c14bd730b620d0d576bda760588e1f2f59a7fcb2f2080577e0085f23a0ca8eadd993b4e61c2ab29549fdb71969afd0" + else + echo "WARNING: add missing hash for your host architecture. To find the value, use: 'find /tmp -name apk.static -exec sha512sum {} \;'" + fi echo "$__ApkToolsSHA512SUM $__ApkToolsDir/apk.static" | sha512sum -c chmod +x "$__ApkToolsDir/apk.static" @@ -477,20 +537,23 @@ if [[ "$__CodeName" == "alpine" ]]; then fi # initialize DB + # shellcheck disable=SC2086 "$__ApkToolsDir/apk.static" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/main" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/community" \ -U $__ApkSignatureArg --root "$__RootfsDir" --arch "$__AlpineArch" --initdb add if [[ "$__AlpineLlvmLibsLookup" == 1 ]]; then + # shellcheck disable=SC2086 __AlpinePackages+=" $("$__ApkToolsDir/apk.static" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/main" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/community" \ -U $__ApkSignatureArg --root "$__RootfsDir" --arch "$__AlpineArch" \ - search 'llvm*-libs' | sort | tail -1 | sed 's/-[^-]*//2g')" + search 'llvm*-libs' | grep -E '^llvm' | sort | tail -1 | sed 's/-[^-]*//2g')" fi # install all packages in one go + # shellcheck disable=SC2086 "$__ApkToolsDir/apk.static" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/main" \ -X "http://dl-cdn.alpinelinux.org/alpine/$version/community" \ @@ -501,12 +564,23 @@ if [[ "$__CodeName" == "alpine" ]]; then elif [[ "$__CodeName" == "freebsd" ]]; then mkdir -p "$__RootfsDir"/usr/local/etc JOBS=${MAXJOBS:="$(getconf _NPROCESSORS_ONLN)"} - wget -O - "https://download.freebsd.org/ftp/releases/${__FreeBSDArch}/${__FreeBSDMachineArch}/${__FreeBSDBase}/base.txz" | tar -C "$__RootfsDir" -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version + + ensureDownloadTool + + if [[ "$__hasWget" == 1 ]]; then + wget -O- "https://download.freebsd.org/ftp/releases/${__FreeBSDArch}/${__FreeBSDMachineArch}/${__FreeBSDBase}/base.txz" | tar -C "$__RootfsDir" -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version + else + curl -SL "https://download.freebsd.org/ftp/releases/${__FreeBSDArch}/${__FreeBSDMachineArch}/${__FreeBSDBase}/base.txz" | tar -C "$__RootfsDir" -Jxf - ./lib ./usr/lib ./usr/libdata ./usr/include ./usr/share/keys ./etc ./bin/freebsd-version + fi echo "ABI = \"FreeBSD:${__FreeBSDABI}:${__FreeBSDMachineArch}\"; FINGERPRINTS = \"${__RootfsDir}/usr/share/keys\"; REPOS_DIR = [\"${__RootfsDir}/etc/pkg\"]; REPO_AUTOUPDATE = NO; RUN_SCRIPTS = NO;" > "${__RootfsDir}"/usr/local/etc/pkg.conf echo "FreeBSD: { url: \"pkg+http://pkg.FreeBSD.org/\${ABI}/quarterly\", mirror_type: \"srv\", signature_type: \"fingerprints\", fingerprints: \"${__RootfsDir}/usr/share/keys/pkg\", enabled: yes }" > "${__RootfsDir}"/etc/pkg/FreeBSD.conf mkdir -p "$__RootfsDir"/tmp # get and build package manager - wget -O - "https://github.com/freebsd/pkg/archive/${__FreeBSDPkg}.tar.gz" | tar -C "$__RootfsDir"/tmp -zxf - + if [[ "$__hasWget" == 1 ]]; then + wget -O- "https://github.com/freebsd/pkg/archive/${__FreeBSDPkg}.tar.gz" | tar -C "$__RootfsDir"/tmp -zxf - + else + curl -SL "https://github.com/freebsd/pkg/archive/${__FreeBSDPkg}.tar.gz" | tar -C "$__RootfsDir"/tmp -zxf - + fi cd "$__RootfsDir/tmp/pkg-${__FreeBSDPkg}" # needed for install to succeed mkdir -p "$__RootfsDir"/host/etc @@ -514,27 +588,43 @@ elif [[ "$__CodeName" == "freebsd" ]]; then rm -rf "$__RootfsDir/tmp/pkg-${__FreeBSDPkg}" # install packages we need. INSTALL_AS_USER=$(whoami) "$__RootfsDir"/host/sbin/pkg -r "$__RootfsDir" -C "$__RootfsDir"/usr/local/etc/pkg.conf update + # shellcheck disable=SC2086 INSTALL_AS_USER=$(whoami) "$__RootfsDir"/host/sbin/pkg -r "$__RootfsDir" -C "$__RootfsDir"/usr/local/etc/pkg.conf install --yes $__FreeBSDPackages elif [[ "$__CodeName" == "illumos" ]]; then mkdir "$__RootfsDir/tmp" pushd "$__RootfsDir/tmp" JOBS=${MAXJOBS:="$(getconf _NPROCESSORS_ONLN)"} + + ensureDownloadTool + echo "Downloading sysroot." - wget -O - https://github.com/illumos/sysroot/releases/download/20181213-de6af22ae73b-v1/illumos-sysroot-i386-20181213-de6af22ae73b-v1.tar.gz | tar -C "$__RootfsDir" -xzf - + if [[ "$__hasWget" == 1 ]]; then + wget -O- https://github.com/illumos/sysroot/releases/download/20181213-de6af22ae73b-v1/illumos-sysroot-i386-20181213-de6af22ae73b-v1.tar.gz | tar -C "$__RootfsDir" -xzf - + else + curl -SL https://github.com/illumos/sysroot/releases/download/20181213-de6af22ae73b-v1/illumos-sysroot-i386-20181213-de6af22ae73b-v1.tar.gz | tar -C "$__RootfsDir" -xzf - + fi echo "Building binutils. Please wait.." - wget -O - https://ftp.gnu.org/gnu/binutils/binutils-2.33.1.tar.bz2 | tar -xjf - + if [[ "$__hasWget" == 1 ]]; then + wget -O- https://ftp.gnu.org/gnu/binutils/binutils-2.42.tar.xz | tar -xJf - + else + curl -SL https://ftp.gnu.org/gnu/binutils/binutils-2.42.tar.xz | tar -xJf - + fi mkdir build-binutils && cd build-binutils - ../binutils-2.33.1/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.10" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" + ../binutils-2.42/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.11" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" make -j "$JOBS" && make install && cd .. echo "Building gcc. Please wait.." - wget -O - https://ftp.gnu.org/gnu/gcc/gcc-8.4.0/gcc-8.4.0.tar.xz | tar -xJf - + if [[ "$__hasWget" == 1 ]]; then + wget -O- https://ftp.gnu.org/gnu/gcc/gcc-13.3.0/gcc-13.3.0.tar.xz | tar -xJf - + else + curl -SL https://ftp.gnu.org/gnu/gcc/gcc-13.3.0/gcc-13.3.0.tar.xz | tar -xJf - + fi CFLAGS="-fPIC" CXXFLAGS="-fPIC" CXXFLAGS_FOR_TARGET="-fPIC" CFLAGS_FOR_TARGET="-fPIC" export CFLAGS CXXFLAGS CXXFLAGS_FOR_TARGET CFLAGS_FOR_TARGET mkdir build-gcc && cd build-gcc - ../gcc-8.4.0/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.10" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ + ../gcc-13.3.0/configure --prefix="$__RootfsDir" --target="${__illumosArch}-sun-solaris2.11" --program-prefix="${__illumosArch}-illumos-" --with-sysroot="$__RootfsDir" --with-gnu-as \ --with-gnu-ld --disable-nls --disable-libgomp --disable-libquadmath --disable-libssp --disable-libvtv --disable-libcilkrts --disable-libada --disable-libsanitizer \ --disable-libquadmath-support --disable-shared --enable-tls make -j "$JOBS" && make install && cd .. @@ -542,9 +632,13 @@ elif [[ "$__CodeName" == "illumos" ]]; then if [[ "$__UseMirror" == 1 ]]; then BaseUrl=https://pkgsrc.smartos.skylime.net fi - BaseUrl="$BaseUrl/packages/SmartOS/trunk/${__illumosArch}/All" + BaseUrl="$BaseUrl/packages/SmartOS/2019Q4/${__illumosArch}/All" echo "Downloading manifest" - wget "$BaseUrl" + if [[ "$__hasWget" == 1 ]]; then + wget "$BaseUrl" + else + curl -SLO "$BaseUrl" + fi echo "Downloading dependencies." read -ra array <<<"$__IllumosPackages" for package in "${array[@]}"; do @@ -552,7 +646,11 @@ elif [[ "$__CodeName" == "illumos" ]]; then # find last occurrence of package in listing and extract its name package="$(sed -En '/.*href="('"$package"'-[0-9].*).tgz".*/h;$!d;g;s//\1/p' All)" echo "Resolved name '$package'" - wget "$BaseUrl"/"$package".tgz + if [[ "$__hasWget" == 1 ]]; then + wget "$BaseUrl"/"$package".tgz + else + curl -SLO "$BaseUrl"/"$package".tgz + fi ar -x "$package".tgz tar --skip-old-files -xzf "$package".tmp.tg* -C "$__RootfsDir" 2>/dev/null done @@ -561,10 +659,17 @@ elif [[ "$__CodeName" == "illumos" ]]; then rm -rf "$__RootfsDir"/{tmp,+*} mkdir -p "$__RootfsDir"/usr/include/net mkdir -p "$__RootfsDir"/usr/include/netpacket - wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/bpf.h - wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/dlt.h - wget -P "$__RootfsDir"/usr/include/netpacket https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/inet/sockmods/netpacket/packet.h - wget -P "$__RootfsDir"/usr/include/sys https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/sys/sdt.h + if [[ "$__hasWget" == 1 ]]; then + wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/bpf.h + wget -P "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/dlt.h + wget -P "$__RootfsDir"/usr/include/netpacket https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/inet/sockmods/netpacket/packet.h + wget -P "$__RootfsDir"/usr/include/sys https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/sys/sdt.h + else + curl -SLO --create-dirs --output-dir "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/bpf.h + curl -SLO --create-dirs --output-dir "$__RootfsDir"/usr/include/net https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/io/bpf/net/dlt.h + curl -SLO --create-dirs --output-dir "$__RootfsDir"/usr/include/netpacket https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/inet/sockmods/netpacket/packet.h + curl -SLO --create-dirs --output-dir "$__RootfsDir"/usr/include/sys https://raw.githubusercontent.com/illumos/illumos-gate/master/usr/src/uts/common/sys/sdt.h + fi elif [[ "$__CodeName" == "haiku" ]]; then JOBS=${MAXJOBS:="$(getconf _NPROCESSORS_ONLN)"} @@ -574,9 +679,16 @@ elif [[ "$__CodeName" == "haiku" ]]; then mkdir "$__RootfsDir/tmp/download" + ensureDownloadTool + echo "Downloading Haiku package tool" - git clone https://github.com/haiku/haiku-toolchains-ubuntu --depth 1 $__RootfsDir/tmp/script - wget -O "$__RootfsDir/tmp/download/hosttools.zip" $($__RootfsDir/tmp/script/fetch.sh --hosttools) + git clone https://github.com/haiku/haiku-toolchains-ubuntu --depth 1 "$__RootfsDir/tmp/script" + if [[ "$__hasWget" == 1 ]]; then + wget -O "$__RootfsDir/tmp/download/hosttools.zip" "$("$__RootfsDir/tmp/script/fetch.sh" --hosttools)" + else + curl -SLo "$__RootfsDir/tmp/download/hosttools.zip" "$("$__RootfsDir/tmp/script/fetch.sh" --hosttools)" + fi + unzip -o "$__RootfsDir/tmp/download/hosttools.zip" -d "$__RootfsDir/tmp/bin" DepotBaseUrl="https://depot.haiku-os.org/__api/v2/pkg/get-pkg" @@ -589,14 +701,25 @@ elif [[ "$__CodeName" == "haiku" ]]; then echo "Downloading $package..." # API documented here: https://github.com/haiku/haikudepotserver/blob/master/haikudepotserver-api2/src/main/resources/api2/pkg.yaml#L60 # The schema here: https://github.com/haiku/haikudepotserver/blob/master/haikudepotserver-api2/src/main/resources/api2/pkg.yaml#L598 - hpkgDownloadUrl="$(wget -qO- --post-data='{"name":"'"$package"'","repositorySourceCode":"haikuports_'$__HaikuArch'","versionType":"LATEST","naturalLanguageCode":"en"}' \ - --header='Content-Type:application/json' "$DepotBaseUrl" | jq -r '.result.versions[].hpkgDownloadURL')" - wget -P "$__RootfsDir/tmp/download" "$hpkgDownloadUrl" + if [[ "$__hasWget" == 1 ]]; then + hpkgDownloadUrl="$(wget -qO- --post-data '{"name":"'"$package"'","repositorySourceCode":"haikuports_'$__HaikuArch'","versionType":"LATEST","naturalLanguageCode":"en"}' \ + --header 'Content-Type:application/json' "$DepotBaseUrl" | jq -r '.result.versions[].hpkgDownloadURL')" + wget -P "$__RootfsDir/tmp/download" "$hpkgDownloadUrl" + else + hpkgDownloadUrl="$(curl -sSL -XPOST --data '{"name":"'"$package"'","repositorySourceCode":"haikuports_'$__HaikuArch'","versionType":"LATEST","naturalLanguageCode":"en"}' \ + --header 'Content-Type:application/json' "$DepotBaseUrl" | jq -r '.result.versions[].hpkgDownloadURL')" + curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$hpkgDownloadUrl" + fi done for package in haiku haiku_devel; do echo "Downloading $package..." - hpkgVersion="$(wget -qO- $HpkgBaseUrl | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" - wget -P "$__RootfsDir/tmp/download" "$HpkgBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" + if [[ "$__hasWget" == 1 ]]; then + hpkgVersion="$(wget -qO- "$HpkgBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" + wget -P "$__RootfsDir/tmp/download" "$HpkgBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" + else + hpkgVersion="$(curl -sSL "$HpkgBaseUrl" | sed -n 's/^.*version: "\([^"]*\)".*$/\1/p')" + curl -SLO --create-dirs --output-dir "$__RootfsDir/tmp/download" "$HpkgBaseUrl/packages/$package-$hpkgVersion-1-$__HaikuArch.hpkg" + fi done # Set up the sysroot @@ -609,7 +732,11 @@ elif [[ "$__CodeName" == "haiku" ]]; then # Download buildtools echo "Downloading Haiku buildtools" - wget -O "$__RootfsDir/tmp/download/buildtools.zip" $($__RootfsDir/tmp/script/fetch.sh --buildtools --arch=$__HaikuArch) + if [[ "$__hasWget" == 1 ]]; then + wget -O "$__RootfsDir/tmp/download/buildtools.zip" "$("$__RootfsDir/tmp/script/fetch.sh" --buildtools --arch=$__HaikuArch)" + else + curl -SLo "$__RootfsDir/tmp/download/buildtools.zip" "$("$__RootfsDir/tmp/script/fetch.sh" --buildtools --arch=$__HaikuArch)" + fi unzip -o "$__RootfsDir/tmp/download/buildtools.zip" -d "$__RootfsDir" # Cleaning up temporary files @@ -622,10 +749,22 @@ elif [[ -n "$__CodeName" ]]; then __Keyring="$__Keyring --force-check-gpg" fi + # shellcheck disable=SC2086 + echo running debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" debootstrap "--variant=minbase" $__Keyring --arch "$__UbuntuArch" "$__CodeName" "$__RootfsDir" "$__UbuntuRepo" - cp "$__CrossDir/$__BuildArch/sources.list.$__CodeName" "$__RootfsDir/etc/apt/sources.list" + + mkdir -p "$__RootfsDir/etc/apt/sources.list.d/" + cat > "$__RootfsDir/etc/apt/sources.list.d/$__CodeName.sources" <>Start configuring Tizen rootfs" ln -sfn asm-${LINK_ARCH} ./usr/include/asm patch -p1 < $__TIZEN_CROSSDIR/tizen.patch +if [[ "$TIZEN_ARCH" == "riscv64" ]]; then + echo "Fixing broken symlinks in $PWD" + rm ./usr/lib64/libresolv.so + ln -s ../../lib64/libresolv.so.2 ./usr/lib64/libresolv.so + rm ./usr/lib64/libpthread.so + ln -s ../../lib64/libpthread.so.0 ./usr/lib64/libpthread.so + rm ./usr/lib64/libdl.so + ln -s ../../lib64/libdl.so.2 ./usr/lib64/libdl.so + rm ./usr/lib64/libutil.so + ln -s ../../lib64/libutil.so.1 ./usr/lib64/libutil.so + rm ./usr/lib64/libm.so + ln -s ../../lib64/libm.so.6 ./usr/lib64/libm.so + rm ./usr/lib64/librt.so + ln -s ../../lib64/librt.so.1 ./usr/lib64/librt.so + rm ./lib/ld-linux-riscv64-lp64d.so.1 + ln -s ../lib64/ld-linux-riscv64-lp64d.so.1 ./lib/ld-linux-riscv64-lp64d.so.1 +fi echo "<:--stdlib=${CLR_CMAKE_CXX_STANDARD_LIBRARY}>) + add_link_options($<$:--stdlib=${CLR_CMAKE_CXX_STANDARD_LIBRARY}>) +endif() + +option(CLR_CMAKE_CXX_STANDARD_LIBRARY_STATIC "Statically link against the C++ standard library" OFF) +if(CLR_CMAKE_CXX_STANDARD_LIBRARY_STATIC) + add_link_options($<$:-static-libstdc++>) +endif() + +set(CLR_CMAKE_CXX_ABI_LIBRARY "" CACHE STRING "C++ ABI implementation library to link against. Only supported with the Clang compiler.") +if (CLR_CMAKE_CXX_ABI_LIBRARY) + # The user may specify the ABI library with the 'lib' prefix, like 'libstdc++'. Strip the prefix here so the linker finds the right library. + string(REGEX REPLACE "^lib(.+)" "\\1" CLR_CMAKE_CXX_ABI_LIBRARY ${CLR_CMAKE_CXX_ABI_LIBRARY}) + # We need to specify this as a linker-backend option as Clang will filter this option out when linking to libc++. + add_link_options("LINKER:-l${CLR_CMAKE_CXX_ABI_LIBRARY}") +endif() + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/eng/common/cross/x86/sources.list.bionic b/eng/common/cross/x86/sources.list.bionic deleted file mode 100644 index a71ccadcffa..00000000000 --- a/eng/common/cross/x86/sources.list.bionic +++ /dev/null @@ -1,11 +0,0 @@ -deb http://archive.ubuntu.com/ubuntu/ bionic main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ bionic main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ bionic-updates main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ bionic-updates main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ bionic-backports main restricted -deb-src http://archive.ubuntu.com/ubuntu/ bionic-backports main restricted - -deb http://archive.ubuntu.com/ubuntu/ bionic-security main restricted universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ bionic-security main restricted universe multiverse diff --git a/eng/common/cross/x86/sources.list.xenial b/eng/common/cross/x86/sources.list.xenial deleted file mode 100644 index ad9c5a0144e..00000000000 --- a/eng/common/cross/x86/sources.list.xenial +++ /dev/null @@ -1,11 +0,0 @@ -deb http://archive.ubuntu.com/ubuntu/ xenial main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ xenial main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ xenial-updates main restricted universe -deb-src http://archive.ubuntu.com/ubuntu/ xenial-updates main restricted universe - -deb http://archive.ubuntu.com/ubuntu/ xenial-backports main restricted -deb-src http://archive.ubuntu.com/ubuntu/ xenial-backports main restricted - -deb http://archive.ubuntu.com/ubuntu/ xenial-security main restricted universe multiverse -deb-src http://archive.ubuntu.com/ubuntu/ xenial-security main restricted universe multiverse diff --git a/eng/common/darc-init.ps1 b/eng/common/darc-init.ps1 index 8fda30bdce2..e3374310563 100644 --- a/eng/common/darc-init.ps1 +++ b/eng/common/darc-init.ps1 @@ -1,6 +1,6 @@ param ( $darcVersion = $null, - $versionEndpoint = 'https://maestro.dot.net/api/assets/darc-version?api-version=2019-01-16', + $versionEndpoint = 'https://maestro.dot.net/api/assets/darc-version?api-version=2020-02-20', $verbosity = 'minimal', $toolpath = $null ) diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh index c305ae6bd77..36dbd45e1ce 100755 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -2,7 +2,7 @@ source="${BASH_SOURCE[0]}" darcVersion='' -versionEndpoint='https://maestro.dot.net/api/assets/darc-version?api-version=2019-01-16' +versionEndpoint='https://maestro.dot.net/api/assets/darc-version?api-version=2020-02-20' verbosity='minimal' while [[ $# > 0 ]]; do diff --git a/eng/common/dotnet-install.sh b/eng/common/dotnet-install.sh index 7e69e3a9e24..7b9d97e3bd4 100755 --- a/eng/common/dotnet-install.sh +++ b/eng/common/dotnet-install.sh @@ -71,6 +71,9 @@ case $cpuname in i[3-6]86) buildarch=x86 ;; + riscv64) + buildarch=riscv64 + ;; *) echo "Unknown CPU $cpuname detected, treating it as x64" buildarch=x64 @@ -82,7 +85,7 @@ if [[ $architecture != "" ]] && [[ $architecture != $buildarch ]]; then dotnetRoot="$dotnetRoot/$architecture" fi -InstallDotNet $dotnetRoot $version "$architecture" $runtime true $runtimeSourceFeed $runtimeSourceFeedKey || { +InstallDotNet "$dotnetRoot" $version "$architecture" $runtime true $runtimeSourceFeed $runtimeSourceFeedKey || { local exit_code=$? Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "dotnet-install.sh failed (exit code '$exit_code')." >&2 ExitWithExitCode $exit_code diff --git a/eng/common/helixpublish.proj b/eng/common/helixpublish.proj index d7f185856e7..c1323bf4121 100644 --- a/eng/common/helixpublish.proj +++ b/eng/common/helixpublish.proj @@ -1,3 +1,4 @@ + diff --git a/eng/common/internal/Directory.Build.props b/eng/common/internal/Directory.Build.props index dbf99d82a5c..f1d041c33da 100644 --- a/eng/common/internal/Directory.Build.props +++ b/eng/common/internal/Directory.Build.props @@ -1,4 +1,11 @@ + + + false + false + + + diff --git a/eng/common/internal/Tools.csproj b/eng/common/internal/Tools.csproj index 7f5ce6d6081..e925952d566 100644 --- a/eng/common/internal/Tools.csproj +++ b/eng/common/internal/Tools.csproj @@ -1,8 +1,8 @@ + net472 - false false @@ -27,4 +27,5 @@ + diff --git a/eng/common/native/CommonLibrary.psm1 b/eng/common/native/CommonLibrary.psm1 index ca38268c44d..f71f6af6cdb 100644 --- a/eng/common/native/CommonLibrary.psm1 +++ b/eng/common/native/CommonLibrary.psm1 @@ -277,7 +277,8 @@ function Get-MachineArchitecture { if (($ProcessorArchitecture -Eq "AMD64") -Or ($ProcessorArchitecture -Eq "IA64") -Or ($ProcessorArchitecture -Eq "ARM64") -Or - ($ProcessorArchitecture -Eq "LOONGARCH64")) { + ($ProcessorArchitecture -Eq "LOONGARCH64") -Or + ($ProcessorArchitecture -Eq "RISCV64")) { return "x64" } return "x86" diff --git a/eng/common/native/init-compiler.sh b/eng/common/native/init-compiler.sh index 2d5660642b8..9a0e1f2b456 100644 --- a/eng/common/native/init-compiler.sh +++ b/eng/common/native/init-compiler.sh @@ -2,7 +2,9 @@ # # This file detects the C/C++ compiler and exports it to the CC/CXX environment variables # -# NOTE: some scripts source this file and rely on stdout being empty, make sure to not output anything here! +# NOTE: some scripts source this file and rely on stdout being empty, make sure +# to not output *anything* here, unless it is an error message that fails the +# build. if [ -z "$build_arch" ] || [ -z "$compiler" ]; then echo "Usage..." @@ -17,11 +19,9 @@ case "$compiler" in # clangx.y or clang-x.y version="$(echo "$compiler" | tr -d '[:alpha:]-=')" majorVersion="${version%%.*}" - [ -z "${version##*.*}" ] && minorVersion="${version#*.}" - if [ -z "$minorVersion" ] && [ -n "$majorVersion" ] && [ "$majorVersion" -le 6 ]; then - minorVersion=0; - fi + # LLVM based on v18 released in early 2024, with two releases per year + maxVersion="$((18 + ((($(date +%Y) - 2024) * 12 + $(date +%-m) - 3) / 6)))" compiler=clang ;; @@ -29,7 +29,9 @@ case "$compiler" in # gccx.y or gcc-x.y version="$(echo "$compiler" | tr -d '[:alpha:]-=')" majorVersion="${version%%.*}" - [ -z "${version##*.*}" ] && minorVersion="${version#*.}" + + # GCC based on v14 released in early 2024, with one release per year + maxVersion="$((14 + ((($(date +%Y) - 2024) * 12 + $(date +%-m) - 3) / 12)))" compiler=gcc ;; esac @@ -47,91 +49,98 @@ check_version_exists() { desired_version=-1 # Set up the environment to be used for building with the desired compiler. - if command -v "$compiler-$1.$2" > /dev/null; then - desired_version="-$1.$2" - elif command -v "$compiler$1$2" > /dev/null; then - desired_version="$1$2" - elif command -v "$compiler-$1$2" > /dev/null; then - desired_version="-$1$2" + if command -v "$compiler-$1" > /dev/null; then + desired_version="-$1" + elif command -v "$compiler$1" > /dev/null; then + desired_version="$1" fi echo "$desired_version" } +__baseOS="$(uname)" +set_compiler_version_from_CC() { + if [ "$__baseOS" = "Darwin" ]; then + # On Darwin, the versions from -version/-dumpversion refer to Xcode + # versions, not llvm versions, so we can't rely on them. + return + fi + + version="$("$CC" -dumpversion)" + if [ -z "$version" ]; then + echo "Error: $CC -dumpversion didn't provide a version" + exit 1 + fi + + # gcc and clang often display 3 part versions. However, gcc can show only 1 part in some environments. + IFS=. read -r majorVersion _ < /dev/null; then - if [ "$(uname)" != "Darwin" ]; then - echo "Warning: Specific version of $compiler not found, falling back to use the one in PATH." - fi - CC="$(command -v "$compiler")" - CXX="$(command -v "$cxxCompiler")" - else - echo "No usable version of $compiler found." + if ! command -v "$compiler" > /dev/null; then + echo "Error: No compatible version of $compiler was found within the range of $minVersion to $maxVersion. Please upgrade your toolchain or specify the compiler explicitly using CLR_CC and CLR_CXX environment variables." exit 1 fi - else - if [ "$compiler" = "clang" ] && [ "$majorVersion" -lt 5 ]; then - if [ "$build_arch" = "arm" ] || [ "$build_arch" = "armel" ]; then - if command -v "$compiler" > /dev/null; then - echo "Warning: Found clang version $majorVersion which is not supported on arm/armel architectures, falling back to use clang from PATH." - CC="$(command -v "$compiler")" - CXX="$(command -v "$cxxCompiler")" - else - echo "Found clang version $majorVersion which is not supported on arm/armel architectures, and there is no clang in PATH." - exit 1 - fi - fi - fi + + CC="$(command -v "$compiler" 2> /dev/null)" + CXX="$(command -v "$cxxCompiler" 2> /dev/null)" + set_compiler_version_from_CC fi else - desired_version="$(check_version_exists "$majorVersion" "$minorVersion")" + desired_version="$(check_version_exists "$majorVersion")" if [ "$desired_version" = "-1" ]; then - echo "Could not find specific version of $compiler: $majorVersion $minorVersion." + echo "Error: Could not find specific version of $compiler: $majorVersion." exit 1 fi fi if [ -z "$CC" ]; then - CC="$(command -v "$compiler$desired_version")" - CXX="$(command -v "$cxxCompiler$desired_version")" - if [ -z "$CXX" ]; then CXX="$(command -v "$cxxCompiler")"; fi + CC="$(command -v "$compiler$desired_version" 2> /dev/null)" + CXX="$(command -v "$cxxCompiler$desired_version" 2> /dev/null)" + if [ -z "$CXX" ]; then CXX="$(command -v "$cxxCompiler" 2> /dev/null)"; fi + set_compiler_version_from_CC fi else if [ ! -f "$CLR_CC" ]; then - echo "CLR_CC is set but path '$CLR_CC' does not exist" + echo "Error: CLR_CC is set but path '$CLR_CC' does not exist" exit 1 fi CC="$CLR_CC" CXX="$CLR_CXX" + set_compiler_version_from_CC fi if [ -z "$CC" ]; then - echo "Unable to find $compiler." + echo "Error: Unable to find $compiler." exit 1 fi -# Only lld version >= 9 can be considered stable. lld doesn't support s390x. -if [ "$compiler" = "clang" ] && [ -n "$majorVersion" ] && [ "$majorVersion" -ge 9 ] && [ "$build_arch" != "s390x" ]; then - if "$CC" -fuse-ld=lld -Wl,--version >/dev/null 2>&1; then - LDFLAGS="-fuse-ld=lld" +if [ "$__baseOS" != "Darwin" ]; then + # On Darwin, we always want to use the Apple linker. + + # Only lld version >= 9 can be considered stable. lld supports s390x starting from 18.0. + if [ "$compiler" = "clang" ] && [ -n "$majorVersion" ] && [ "$majorVersion" -ge 9 ] && { [ "$build_arch" != "s390x" ] || [ "$majorVersion" -ge 18 ]; }; then + if "$CC" -fuse-ld=lld -Wl,--version >/dev/null 2>&1; then + LDFLAGS="-fuse-ld=lld" + fi fi fi -SCAN_BUILD_COMMAND="$(command -v "scan-build$desired_version")" +SCAN_BUILD_COMMAND="$(command -v "scan-build$desired_version" 2> /dev/null)" export CC CXX LDFLAGS SCAN_BUILD_COMMAND diff --git a/eng/common/native/init-distro-rid.sh b/eng/common/native/init-distro-rid.sh index de1687b2ccb..83ea7aab0e0 100644 --- a/eng/common/native/init-distro-rid.sh +++ b/eng/common/native/init-distro-rid.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/bin/sh # getNonPortableDistroRid # @@ -11,21 +11,16 @@ # non-portable rid getNonPortableDistroRid() { - local targetOs="$1" - local targetArch="$2" - local rootfsDir="$3" - local nonPortableRid="" + targetOs="$1" + targetArch="$2" + rootfsDir="$3" + nonPortableRid="" if [ "$targetOs" = "linux" ]; then + # shellcheck disable=SC1091 if [ -e "${rootfsDir}/etc/os-release" ]; then - source "${rootfsDir}/etc/os-release" - - if [[ "${ID}" == "rhel" || "${ID}" == "rocky" || "${ID}" == "alpine" ]]; then - # remove the last version digit - VERSION_ID="${VERSION_ID%.*}" - fi - - if [[ "${VERSION_ID:-}" =~ ^([[:digit:]]|\.)+$ ]]; then + . "${rootfsDir}/etc/os-release" + if echo "${VERSION_ID:-}" | grep -qE '^([[:digit:]]|\.)+$'; then nonPortableRid="${ID}.${VERSION_ID}-${targetArch}" else # Rolling release distros either do not set VERSION_ID, set it as blank or @@ -33,45 +28,33 @@ getNonPortableDistroRid() # so omit it here to be consistent with everything else. nonPortableRid="${ID}-${targetArch}" fi - elif [ -e "${rootfsDir}/android_platform" ]; then - source "$rootfsDir"/android_platform + # shellcheck disable=SC1091 + . "${rootfsDir}/android_platform" nonPortableRid="$RID" fi fi if [ "$targetOs" = "freebsd" ]; then - # $rootfsDir can be empty. freebsd-version is shell script and it should always work. - __freebsd_major_version=$($rootfsDir/bin/freebsd-version | { read v; echo "${v%%.*}"; }) + # $rootfsDir can be empty. freebsd-version is a shell script and should always work. + __freebsd_major_version=$("$rootfsDir"/bin/freebsd-version | cut -d'.' -f1) nonPortableRid="freebsd.$__freebsd_major_version-${targetArch}" - elif command -v getprop && getprop ro.product.system.model 2>&1 | grep -qi android; then + elif command -v getprop >/dev/null && getprop ro.product.system.model | grep -qi android; then __android_sdk_version=$(getprop ro.build.version.sdk) nonPortableRid="android.$__android_sdk_version-${targetArch}" elif [ "$targetOs" = "illumos" ]; then __uname_version=$(uname -v) - case "$__uname_version" in - omnios-*) - __omnios_major_version=$(echo "${__uname_version:8:2}") - nonPortableRid=omnios."$__omnios_major_version"-"$targetArch" - ;; - joyent_*) - __smartos_major_version=$(echo "${__uname_version:7:4}") - nonPortableRid=smartos."$__smartos_major_version"-"$targetArch" - ;; - illumos_*) - nonPortableRid=openindiana-"$targetArch" - ;; - esac + nonPortableRid="illumos-${targetArch}" elif [ "$targetOs" = "solaris" ]; then __uname_version=$(uname -v) - __solaris_major_version=$(echo "${__uname_version%.*}") - nonPortableRid=solaris."$__solaris_major_version"-"$targetArch" + __solaris_major_version=$(echo "$__uname_version" | cut -d'.' -f1) + nonPortableRid="solaris.$__solaris_major_version-${targetArch}" elif [ "$targetOs" = "haiku" ]; then - __uname_release=$(uname -r) + __uname_release="$(uname -r)" nonPortableRid=haiku.r"$__uname_release"-"$targetArch" fi - echo "$(echo $nonPortableRid | tr '[:upper:]' '[:lower:]')" + echo "$nonPortableRid" | tr '[:upper:]' '[:lower:]' } # initDistroRidGlobal @@ -85,26 +68,23 @@ getNonPortableDistroRid() # None # # Notes: -# -# It is important to note that the function does not return anything, but it -# exports the following variables on success: -# -# __DistroRid : Non-portable rid of the target platform. -# __PortableTargetOS : OS-part of the portable rid that corresponds to the target platform. -# +# It is important to note that the function does not return anything, but it +# exports the following variables on success: +# __DistroRid : Non-portable rid of the target platform. +# __PortableTargetOS : OS-part of the portable rid that corresponds to the target platform. initDistroRidGlobal() { - local targetOs="$1" - local targetArch="$2" - local rootfsDir="" - if [ "$#" -ge 3 ]; then + targetOs="$1" + targetArch="$2" + rootfsDir="" + if [ $# -ge 3 ]; then rootfsDir="$3" fi if [ -n "${rootfsDir}" ]; then # We may have a cross build. Check for the existence of the rootfsDir if [ ! -e "${rootfsDir}" ]; then - echo "Error rootfsDir has been passed, but the location is not valid." + echo "Error: rootfsDir has been passed, but the location is not valid." exit 1 fi fi @@ -119,7 +99,7 @@ initDistroRidGlobal() STRINGS="$(command -v llvm-strings || true)" fi - # Check for musl-based distros (e.g Alpine Linux, Void Linux). + # Check for musl-based distros (e.g. Alpine Linux, Void Linux). if "${rootfsDir}/usr/bin/ldd" --version 2>&1 | grep -q musl || ( [ -n "$STRINGS" ] && "$STRINGS" "${rootfsDir}/usr/bin/ldd" 2>&1 | grep -q musl ); then __PortableTargetOS="linux-musl" diff --git a/eng/common/native/init-os-and-arch.sh b/eng/common/native/init-os-and-arch.sh index e693617a6c2..38921d4338f 100644 --- a/eng/common/native/init-os-and-arch.sh +++ b/eng/common/native/init-os-and-arch.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/bin/sh # Use uname to determine what the OS is. OSName=$(uname -s | tr '[:upper:]' '[:lower:]') @@ -35,6 +35,10 @@ fi case "$CPUName" in arm64|aarch64) arch=arm64 + if [ "$(getconf LONG_BIT)" -lt 64 ]; then + # This is 32-bit OS running on 64-bit CPU (for example Raspberry Pi OS) + arch=arm + fi ;; loongarch64) @@ -50,6 +54,7 @@ case "$CPUName" in ;; armv7l|armv8l) + # shellcheck disable=SC1091 if (NAME=""; . /etc/os-release; test "$NAME" = "Tizen"); then arch=armel else diff --git a/eng/common/post-build/add-build-to-channel.ps1 b/eng/common/post-build/add-build-to-channel.ps1 deleted file mode 100644 index 49938f0c89f..00000000000 --- a/eng/common/post-build/add-build-to-channel.ps1 +++ /dev/null @@ -1,48 +0,0 @@ -param( - [Parameter(Mandatory=$true)][int] $BuildId, - [Parameter(Mandatory=$true)][int] $ChannelId, - [Parameter(Mandatory=$true)][string] $MaestroApiAccessToken, - [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', - [Parameter(Mandatory=$false)][string] $MaestroApiVersion = '2019-01-16' -) - -try { - . $PSScriptRoot\post-build-utils.ps1 - - # Check that the channel we are going to promote the build to exist - $channelInfo = Get-MaestroChannel -ChannelId $ChannelId - - if (!$channelInfo) { - Write-PipelineTelemetryCategory -Category 'PromoteBuild' -Message "Channel with BAR ID $ChannelId was not found in BAR!" - ExitWithExitCode 1 - } - - # Get info about which channel(s) the build has already been promoted to - $buildInfo = Get-MaestroBuild -BuildId $BuildId - - if (!$buildInfo) { - Write-PipelineTelemetryError -Category 'PromoteBuild' -Message "Build with BAR ID $BuildId was not found in BAR!" - ExitWithExitCode 1 - } - - # Find whether the build is already assigned to the channel or not - if ($buildInfo.channels) { - foreach ($channel in $buildInfo.channels) { - if ($channel.Id -eq $ChannelId) { - Write-Host "The build with BAR ID $BuildId is already on channel $ChannelId!" - ExitWithExitCode 0 - } - } - } - - Write-Host "Promoting build '$BuildId' to channel '$ChannelId'." - - Assign-BuildToChannel -BuildId $BuildId -ChannelId $ChannelId - - Write-Host 'done.' -} -catch { - Write-Host $_ - Write-PipelineTelemetryError -Category 'PromoteBuild' -Message "There was an error while trying to promote build '$BuildId' to channel '$ChannelId'" - ExitWithExitCode 1 -} diff --git a/eng/common/post-build/check-channel-consistency.ps1 b/eng/common/post-build/check-channel-consistency.ps1 index 63f3464c986..61208d2d135 100644 --- a/eng/common/post-build/check-channel-consistency.ps1 +++ b/eng/common/post-build/check-channel-consistency.ps1 @@ -4,10 +4,18 @@ param( ) try { - . $PSScriptRoot\post-build-utils.ps1 + $ErrorActionPreference = 'Stop' + Set-StrictMode -Version 2.0 + + # `tools.ps1` checks $ci to perform some actions. Since the post-build + # scripts don't necessarily execute in the same agent that run the + # build.ps1/sh script this variable isn't automatically set. + $ci = $true + $disableConfigureToolsetImport = $true + . $PSScriptRoot\..\tools.ps1 if ($PromoteToChannels -eq "") { - Write-PipelineTaskError -Type 'warning' -Message "This build won't publish assets as it's not configured to any Maestro channel. If that wasn't intended use Darc to configure a default channel using add-default-channel for this branch or to promote it to a channel using add-build-to-channel. See https://github.com/dotnet/arcade/blob/master/Documentation/Darc.md#assigning-an-individual-build-to-a-channel for more info." + Write-PipelineTaskError -Type 'warning' -Message "This build won't publish assets as it's not configured to any Maestro channel. If that wasn't intended use Darc to configure a default channel using add-default-channel for this branch or to promote it to a channel using add-build-to-channel. See https://github.com/dotnet/arcade/blob/main/Documentation/Darc.md#assigning-an-individual-build-to-a-channel for more info." ExitWithExitCode 0 } diff --git a/eng/common/post-build/nuget-validation.ps1 b/eng/common/post-build/nuget-validation.ps1 index dab3534ab53..e5de00c8983 100644 --- a/eng/common/post-build/nuget-validation.ps1 +++ b/eng/common/post-build/nuget-validation.ps1 @@ -2,20 +2,18 @@ # tool: https://github.com/NuGet/NuGetGallery/tree/jver-verify/src/VerifyMicrosoftPackage param( - [Parameter(Mandatory=$true)][string] $PackagesPath, # Path to where the packages to be validated are - [Parameter(Mandatory=$true)][string] $ToolDestinationPath # Where the validation tool should be downloaded to + [Parameter(Mandatory=$true)][string] $PackagesPath # Path to where the packages to be validated are ) -try { - . $PSScriptRoot\post-build-utils.ps1 - - $url = 'https://raw.githubusercontent.com/NuGet/NuGetGallery/3e25ad135146676bcab0050a516939d9958bfa5d/src/VerifyMicrosoftPackage/verify.ps1' - - New-Item -ItemType 'directory' -Path ${ToolDestinationPath} -Force +# `tools.ps1` checks $ci to perform some actions. Since the post-build +# scripts don't necessarily execute in the same agent that run the +# build.ps1/sh script this variable isn't automatically set. +$ci = $true +$disableConfigureToolsetImport = $true +. $PSScriptRoot\..\tools.ps1 - Invoke-WebRequest $url -OutFile ${ToolDestinationPath}\verify.ps1 - - & ${ToolDestinationPath}\verify.ps1 ${PackagesPath}\*.nupkg +try { + & $PSScriptRoot\nuget-verification.ps1 ${PackagesPath}\*.nupkg } catch { Write-Host $_.ScriptStackTrace diff --git a/eng/common/post-build/nuget-verification.ps1 b/eng/common/post-build/nuget-verification.ps1 new file mode 100644 index 00000000000..a365194a938 --- /dev/null +++ b/eng/common/post-build/nuget-verification.ps1 @@ -0,0 +1,121 @@ +<# +.SYNOPSIS + Verifies that Microsoft NuGet packages have proper metadata. +.DESCRIPTION + Downloads a verification tool and runs metadata validation on the provided NuGet packages. This script writes an + error if any of the provided packages fail validation. All arguments provided to this PowerShell script that do not + match PowerShell parameters are passed on to the verification tool downloaded during the execution of this script. +.PARAMETER NuGetExePath + The path to the nuget.exe binary to use. If not provided, nuget.exe will be downloaded into the -DownloadPath + directory. +.PARAMETER PackageSource + The package source to use to download the verification tool. If not provided, nuget.org will be used. +.PARAMETER DownloadPath + The directory path to download the verification tool and nuget.exe to. If not provided, + %TEMP%\NuGet.VerifyNuGetPackage will be used. +.PARAMETER args + Arguments that will be passed to the verification tool. +.EXAMPLE + PS> .\verify.ps1 *.nupkg + Verifies the metadata of all .nupkg files in the currect working directory. +.EXAMPLE + PS> .\verify.ps1 --help + Displays the help text of the downloaded verifiction tool. +.LINK + https://github.com/NuGet/NuGetGallery/blob/master/src/VerifyMicrosoftPackage/README.md +#> + +# This script was copied from https://github.com/NuGet/NuGetGallery/blob/3e25ad135146676bcab0050a516939d9958bfa5d/src/VerifyMicrosoftPackage/verify.ps1 + +[CmdletBinding(PositionalBinding = $false)] +param( + [string]$NuGetExePath, + [string]$PackageSource = "https://api.nuget.org/v3/index.json", + [string]$DownloadPath, + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$args +) + +# The URL to download nuget.exe. +$nugetExeUrl = "https://dist.nuget.org/win-x86-commandline/v4.9.4/nuget.exe" + +# The package ID of the verification tool. +$packageId = "NuGet.VerifyMicrosoftPackage" + +# The location that nuget.exe and the verification tool will be downloaded to. +if (!$DownloadPath) { + $DownloadPath = (Join-Path $env:TEMP "NuGet.VerifyMicrosoftPackage") +} + +$fence = New-Object -TypeName string -ArgumentList '=', 80 + +# Create the download directory, if it doesn't already exist. +if (!(Test-Path $DownloadPath)) { + New-Item -ItemType Directory $DownloadPath | Out-Null +} +Write-Host "Using download path: $DownloadPath" + +if ($NuGetExePath) { + $nuget = $NuGetExePath +} else { + $downloadedNuGetExe = Join-Path $DownloadPath "nuget.exe" + + # Download nuget.exe, if it doesn't already exist. + if (!(Test-Path $downloadedNuGetExe)) { + Write-Host "Downloading nuget.exe from $nugetExeUrl..." + $ProgressPreference = 'SilentlyContinue' + try { + Invoke-WebRequest $nugetExeUrl -OutFile $downloadedNuGetExe + $ProgressPreference = 'Continue' + } catch { + $ProgressPreference = 'Continue' + Write-Error $_ + Write-Error "nuget.exe failed to download." + exit + } + } + + $nuget = $downloadedNuGetExe +} + +Write-Host "Using nuget.exe path: $nuget" +Write-Host " " + +# Download the latest version of the verification tool. +Write-Host "Downloading the latest version of $packageId from $packageSource..." +Write-Host $fence +& $nuget install $packageId ` + -Prerelease ` + -OutputDirectory $DownloadPath ` + -Source $PackageSource +Write-Host $fence +Write-Host " " + +if ($LASTEXITCODE -ne 0) { + Write-Error "nuget.exe failed to fetch the verify tool." + exit +} + +# Find the most recently downloaded tool +Write-Host "Finding the most recently downloaded verification tool." +$verifyProbePath = Join-Path $DownloadPath "$packageId.*" +$verifyPath = Get-ChildItem -Path $verifyProbePath -Directory ` + | Sort-Object -Property LastWriteTime -Descending ` + | Select-Object -First 1 +$verify = Join-Path $verifyPath "tools\NuGet.VerifyMicrosoftPackage.exe" +Write-Host "Using verification tool: $verify" +Write-Host " " + +# Execute the verification tool. +Write-Host "Executing the verify tool..." +Write-Host $fence +& $verify $args +Write-Host $fence +Write-Host " " + +# Respond to the exit code. +if ($LASTEXITCODE -ne 0) { + Write-Error "The verify tool found some problems." +} else { + Write-Output "The verify tool succeeded." +} diff --git a/eng/common/post-build/post-build-utils.ps1 b/eng/common/post-build/post-build-utils.ps1 deleted file mode 100644 index 534f6988d5b..00000000000 --- a/eng/common/post-build/post-build-utils.ps1 +++ /dev/null @@ -1,91 +0,0 @@ -# Most of the functions in this file require the variables `MaestroApiEndPoint`, -# `MaestroApiVersion` and `MaestroApiAccessToken` to be globally available. - -$ErrorActionPreference = 'Stop' -Set-StrictMode -Version 2.0 - -# `tools.ps1` checks $ci to perform some actions. Since the post-build -# scripts don't necessarily execute in the same agent that run the -# build.ps1/sh script this variable isn't automatically set. -$ci = $true -$disableConfigureToolsetImport = $true -. $PSScriptRoot\..\tools.ps1 - -function Create-MaestroApiRequestHeaders([string]$ContentType = 'application/json') { - Validate-MaestroVars - - $headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' - $headers.Add('Accept', $ContentType) - $headers.Add('Authorization',"Bearer $MaestroApiAccessToken") - return $headers -} - -function Get-MaestroChannel([int]$ChannelId) { - Validate-MaestroVars - - $apiHeaders = Create-MaestroApiRequestHeaders - $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}?api-version=$MaestroApiVersion" - - $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } - return $result -} - -function Get-MaestroBuild([int]$BuildId) { - Validate-MaestroVars - - $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken - $apiEndpoint = "$MaestroApiEndPoint/api/builds/${BuildId}?api-version=$MaestroApiVersion" - - $result = try { return Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } - return $result -} - -function Get-MaestroSubscriptions([string]$SourceRepository, [int]$ChannelId) { - Validate-MaestroVars - - $SourceRepository = [System.Web.HttpUtility]::UrlEncode($SourceRepository) - $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken - $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions?sourceRepository=$SourceRepository&channelId=$ChannelId&api-version=$MaestroApiVersion" - - $result = try { Invoke-WebRequest -Method Get -Uri $apiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } - return $result -} - -function Assign-BuildToChannel([int]$BuildId, [int]$ChannelId) { - Validate-MaestroVars - - $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken - $apiEndpoint = "$MaestroApiEndPoint/api/channels/${ChannelId}/builds/${BuildId}?api-version=$MaestroApiVersion" - Invoke-WebRequest -Method Post -Uri $apiEndpoint -Headers $apiHeaders | Out-Null -} - -function Trigger-Subscription([string]$SubscriptionId) { - Validate-MaestroVars - - $apiHeaders = Create-MaestroApiRequestHeaders -AuthToken $MaestroApiAccessToken - $apiEndpoint = "$MaestroApiEndPoint/api/subscriptions/$SubscriptionId/trigger?api-version=$MaestroApiVersion" - Invoke-WebRequest -Uri $apiEndpoint -Headers $apiHeaders -Method Post | Out-Null -} - -function Validate-MaestroVars { - try { - Get-Variable MaestroApiEndPoint | Out-Null - Get-Variable MaestroApiVersion | Out-Null - Get-Variable MaestroApiAccessToken | Out-Null - - if (!($MaestroApiEndPoint -Match '^http[s]?://maestro-(int|prod).westus2.cloudapp.azure.com$')) { - Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiEndPoint is not a valid Maestro URL. '$MaestroApiEndPoint'" - ExitWithExitCode 1 - } - - if (!($MaestroApiVersion -Match '^[0-9]{4}-[0-9]{2}-[0-9]{2}$')) { - Write-PipelineTelemetryError -Category 'MaestroVars' -Message "MaestroApiVersion does not match a version string in the format yyyy-MM-DD. '$MaestroApiVersion'" - ExitWithExitCode 1 - } - } - catch { - Write-PipelineTelemetryError -Category 'MaestroVars' -Message 'Error: Variables `MaestroApiEndPoint`, `MaestroApiVersion` and `MaestroApiAccessToken` are required while using this script.' - Write-Host $_ - ExitWithExitCode 1 - } -} diff --git a/eng/common/post-build/publish-using-darc.ps1 b/eng/common/post-build/publish-using-darc.ps1 index 238945cb5ab..90b58e32a87 100644 --- a/eng/common/post-build/publish-using-darc.ps1 +++ b/eng/common/post-build/publish-using-darc.ps1 @@ -9,7 +9,12 @@ param( ) try { - . $PSScriptRoot\post-build-utils.ps1 + # `tools.ps1` checks $ci to perform some actions. Since the post-build + # scripts don't necessarily execute in the same agent that run the + # build.ps1/sh script this variable isn't automatically set. + $ci = $true + $disableConfigureToolsetImport = $true + . $PSScriptRoot\..\tools.ps1 $darc = Get-Darc @@ -37,6 +42,7 @@ try { --azdev-pat "$AzdoToken" ` --bar-uri "$MaestroApiEndPoint" ` --ci ` + --verbose ` @optionalParams if ($LastExitCode -ne 0) { diff --git a/eng/common/post-build/redact-logs.ps1 b/eng/common/post-build/redact-logs.ps1 new file mode 100644 index 00000000000..b7fc1959150 --- /dev/null +++ b/eng/common/post-build/redact-logs.ps1 @@ -0,0 +1,89 @@ +[CmdletBinding(PositionalBinding=$False)] +param( + [Parameter(Mandatory=$true, Position=0)][string] $InputPath, + [Parameter(Mandatory=$true)][string] $BinlogToolVersion, + [Parameter(Mandatory=$false)][string] $DotnetPath, + [Parameter(Mandatory=$false)][string] $PackageFeed = 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json', + # File with strings to redact - separated by newlines. + # For comments start the line with '# ' - such lines are ignored + [Parameter(Mandatory=$false)][string] $TokensFilePath, + [Parameter(ValueFromRemainingArguments=$true)][String[]]$TokensToRedact +) + +try { + $ErrorActionPreference = 'Stop' + Set-StrictMode -Version 2.0 + + # `tools.ps1` checks $ci to perform some actions. Since the post-build + # scripts don't necessarily execute in the same agent that run the + # build.ps1/sh script this variable isn't automatically set. + $ci = $true + $disableConfigureToolsetImport = $true + . $PSScriptRoot\..\tools.ps1 + + $packageName = 'binlogtool' + + $dotnet = $DotnetPath + + if (!$dotnet) { + $dotnetRoot = InitializeDotNetCli -install:$true + $dotnet = "$dotnetRoot\dotnet.exe" + } + + $toolList = & "$dotnet" tool list -g + + if ($toolList -like "*$packageName*") { + & "$dotnet" tool uninstall $packageName -g + } + + $toolPath = "$PSScriptRoot\..\..\..\.tools" + $verbosity = 'minimal' + + New-Item -ItemType Directory -Force -Path $toolPath + + Push-Location -Path $toolPath + + try { + Write-Host "Installing Binlog redactor CLI..." + Write-Host "'$dotnet' new tool-manifest" + & "$dotnet" new tool-manifest + Write-Host "'$dotnet' tool install $packageName --local --add-source '$PackageFeed' -v $verbosity --version $BinlogToolVersion" + & "$dotnet" tool install $packageName --local --add-source "$PackageFeed" -v $verbosity --version $BinlogToolVersion + + if (Test-Path $TokensFilePath) { + Write-Host "Adding additional sensitive data for redaction from file: " $TokensFilePath + $TokensToRedact += Get-Content -Path $TokensFilePath | Foreach {$_.Trim()} | Where { $_ -notmatch "^# " } + } + + $optionalParams = [System.Collections.ArrayList]::new() + + Foreach ($p in $TokensToRedact) + { + if($p -match '^\$\(.*\)$') + { + Write-Host ("Ignoring token {0} as it is probably unexpanded AzDO variable" -f $p) + } + elseif($p) + { + $optionalParams.Add("-p:" + $p) | Out-Null + } + } + + & $dotnet binlogtool redact --input:$InputPath --recurse --in-place ` + @optionalParams + + if ($LastExitCode -ne 0) { + Write-PipelineTelemetryError -Category 'Redactor' -Type 'warning' -Message "Problems using Redactor tool (exit code: $LastExitCode). But ignoring them now." + } + } + finally { + Pop-Location + } + + Write-Host 'done.' +} +catch { + Write-Host $_ + Write-PipelineTelemetryError -Category 'Redactor' -Message "There was an error while trying to redact logs. Error: $_" + ExitWithExitCode 1 +} diff --git a/eng/common/post-build/sourcelink-validation.ps1 b/eng/common/post-build/sourcelink-validation.ps1 index 4011d324e73..1976ef70fb8 100644 --- a/eng/common/post-build/sourcelink-validation.ps1 +++ b/eng/common/post-build/sourcelink-validation.ps1 @@ -6,7 +6,15 @@ param( [Parameter(Mandatory=$true)][string] $SourcelinkCliVersion # Version of SourceLink CLI to use ) -. $PSScriptRoot\post-build-utils.ps1 +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2.0 + +# `tools.ps1` checks $ci to perform some actions. Since the post-build +# scripts don't necessarily execute in the same agent that run the +# build.ps1/sh script this variable isn't automatically set. +$ci = $true +$disableConfigureToolsetImport = $true +. $PSScriptRoot\..\tools.ps1 # Cache/HashMap (File -> Exist flag) used to consult whether a file exist # in the repository at a specific commit point. This is populated by inserting diff --git a/eng/common/post-build/symbols-validation.ps1 b/eng/common/post-build/symbols-validation.ps1 index cd2181bafa0..7146e593ffa 100644 --- a/eng/common/post-build/symbols-validation.ps1 +++ b/eng/common/post-build/symbols-validation.ps1 @@ -322,8 +322,6 @@ function InstallDotnetSymbol { } try { - . $PSScriptRoot\post-build-utils.ps1 - InstallDotnetSymbol foreach ($Job in @(Get-Job)) { diff --git a/eng/common/post-build/trigger-subscriptions.ps1 b/eng/common/post-build/trigger-subscriptions.ps1 deleted file mode 100644 index ac9a95778fc..00000000000 --- a/eng/common/post-build/trigger-subscriptions.ps1 +++ /dev/null @@ -1,64 +0,0 @@ -param( - [Parameter(Mandatory=$true)][string] $SourceRepo, - [Parameter(Mandatory=$true)][int] $ChannelId, - [Parameter(Mandatory=$true)][string] $MaestroApiAccessToken, - [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro.dot.net', - [Parameter(Mandatory=$false)][string] $MaestroApiVersion = '2019-01-16' -) - -try { - . $PSScriptRoot\post-build-utils.ps1 - - # Get all the $SourceRepo subscriptions - $normalizedSourceRepo = $SourceRepo.Replace('dnceng@', '') - $subscriptions = Get-MaestroSubscriptions -SourceRepository $normalizedSourceRepo -ChannelId $ChannelId - - if (!$subscriptions) { - Write-PipelineTelemetryError -Category 'TriggerSubscriptions' -Message "No subscriptions found for source repo '$normalizedSourceRepo' in channel '$ChannelId'" - ExitWithExitCode 0 - } - - $subscriptionsToTrigger = New-Object System.Collections.Generic.List[string] - $failedTriggeredSubscription = $false - - # Get all enabled subscriptions that need dependency flow on 'everyBuild' - foreach ($subscription in $subscriptions) { - if ($subscription.enabled -and $subscription.policy.updateFrequency -like 'everyBuild' -and $subscription.channel.id -eq $ChannelId) { - Write-Host "Should trigger this subscription: ${$subscription.id}" - [void]$subscriptionsToTrigger.Add($subscription.id) - } - } - - foreach ($subscriptionToTrigger in $subscriptionsToTrigger) { - try { - Write-Host "Triggering subscription '$subscriptionToTrigger'." - - Trigger-Subscription -SubscriptionId $subscriptionToTrigger - - Write-Host 'done.' - } - catch - { - Write-Host "There was an error while triggering subscription '$subscriptionToTrigger'" - Write-Host $_ - Write-Host $_.ScriptStackTrace - $failedTriggeredSubscription = $true - } - } - - if ($subscriptionsToTrigger.Count -eq 0) { - Write-Host "No subscription matched source repo '$normalizedSourceRepo' and channel ID '$ChannelId'." - } - elseif ($failedTriggeredSubscription) { - Write-PipelineTelemetryError -Category 'TriggerSubscriptions' -Message 'At least one subscription failed to be triggered...' - ExitWithExitCode 1 - } - else { - Write-Host 'All subscriptions were triggered successfully!' - } -} -catch { - Write-Host $_.ScriptStackTrace - Write-PipelineTelemetryError -Category 'TriggerSubscriptions' -Message $_ - ExitWithExitCode 1 -} diff --git a/eng/common/sdk-task.ps1 b/eng/common/sdk-task.ps1 index 73828dd30d3..aab40de3fd9 100644 --- a/eng/common/sdk-task.ps1 +++ b/eng/common/sdk-task.ps1 @@ -64,7 +64,7 @@ try { $GlobalJson.tools | Add-Member -Name "vs" -Value (ConvertFrom-Json "{ `"version`": `"16.5`" }") -MemberType NoteProperty } if( -not ($GlobalJson.tools.PSObject.Properties.Name -match "xcopy-msbuild" )) { - $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.8.1-2" -MemberType NoteProperty + $GlobalJson.tools | Add-Member -Name "xcopy-msbuild" -Value "17.10.0-pre.4.0" -MemberType NoteProperty } if ($GlobalJson.tools."xcopy-msbuild".Trim() -ine "none") { $xcopyMSBuildToolsFolder = InitializeXCopyMSBuild $GlobalJson.tools."xcopy-msbuild" -install $true diff --git a/eng/common/sdl/NuGet.config b/eng/common/sdl/NuGet.config index 5bfbb02ef04..3849bdb3cf5 100644 --- a/eng/common/sdl/NuGet.config +++ b/eng/common/sdl/NuGet.config @@ -5,11 +5,11 @@ - + - + diff --git a/eng/common/sdl/execute-all-sdl-tools.ps1 b/eng/common/sdl/execute-all-sdl-tools.ps1 index 81ded5b7f47..4715d75e974 100644 --- a/eng/common/sdl/execute-all-sdl-tools.ps1 +++ b/eng/common/sdl/execute-all-sdl-tools.ps1 @@ -6,6 +6,7 @@ Param( [string] $BranchName=$env:BUILD_SOURCEBRANCH, # Optional: name of branch or version of gdn settings; defaults to master [string] $SourceDirectory=$env:BUILD_SOURCESDIRECTORY, # Required: the directory where source files are located [string] $ArtifactsDirectory = (Join-Path $env:BUILD_ARTIFACTSTAGINGDIRECTORY ('artifacts')), # Required: the directory where build artifacts are located + [string] $AzureDevOpsAccessToken, # Required: access token for dnceng; should be provided via KeyVault # Optional: list of SDL tools to run on source code. See 'configure-sdl-tool.ps1' for tools list # format. @@ -74,7 +75,7 @@ try { } Exec-BlockVerbosely { - & $(Join-Path $PSScriptRoot 'init-sdl.ps1') -GuardianCliLocation $guardianCliLocation -Repository $RepoName -BranchName $BranchName -WorkingDirectory $workingDirectory -GuardianLoggerLevel $GuardianLoggerLevel + & $(Join-Path $PSScriptRoot 'init-sdl.ps1') -GuardianCliLocation $guardianCliLocation -Repository $RepoName -BranchName $BranchName -WorkingDirectory $workingDirectory -AzureDevOpsAccessToken $AzureDevOpsAccessToken -GuardianLoggerLevel $GuardianLoggerLevel } $gdnFolder = Join-Path $workingDirectory '.gdn' @@ -103,6 +104,7 @@ try { -TargetDirectory $targetDirectory ` -GdnFolder $gdnFolder ` -ToolsList $tools ` + -AzureDevOpsAccessToken $AzureDevOpsAccessToken ` -GuardianLoggerLevel $GuardianLoggerLevel ` -CrScanAdditionalRunConfigParams $CrScanAdditionalRunConfigParams ` -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams ` diff --git a/eng/common/sdl/init-sdl.ps1 b/eng/common/sdl/init-sdl.ps1 index 588ff8e22fb..3ac1d92b370 100644 --- a/eng/common/sdl/init-sdl.ps1 +++ b/eng/common/sdl/init-sdl.ps1 @@ -3,6 +3,7 @@ Param( [string] $Repository, [string] $BranchName='master', [string] $WorkingDirectory, + [string] $AzureDevOpsAccessToken, [string] $GuardianLoggerLevel='Standard' ) @@ -20,7 +21,14 @@ $ci = $true # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' +# Construct basic auth from AzDO access token; construct URI to the repository's gdn folder stored in that repository; construct location of zip file +$encodedPat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$AzureDevOpsAccessToken")) +$escapedRepository = [Uri]::EscapeDataString("/$Repository/$BranchName/.gdn") +$uri = "https://dev.azure.com/dnceng/internal/_apis/git/repositories/sdl-tool-cfg/Items?path=$escapedRepository&versionDescriptor[versionOptions]=0&`$format=zip&api-version=5.0" +$zipFile = "$WorkingDirectory/gdn.zip" + Add-Type -AssemblyName System.IO.Compression.FileSystem +$gdnFolder = (Join-Path $WorkingDirectory '.gdn') try { # if the folder does not exist, we'll do a guardian init and push it to the remote repository diff --git a/eng/common/sdl/sdl.ps1 b/eng/common/sdl/sdl.ps1 index 7fe603fe995..648c5068d7d 100644 --- a/eng/common/sdl/sdl.ps1 +++ b/eng/common/sdl/sdl.ps1 @@ -4,8 +4,6 @@ function Install-Gdn { [Parameter(Mandatory=$true)] [string]$Path, - [string]$Source = "https://pkgs.dev.azure.com/dnceng/_packaging/Guardian1ESPTUpstreamOrgFeed/nuget/v3/index.json", - # If omitted, install the latest version of Guardian, otherwise install that specific version. [string]$Version ) @@ -21,7 +19,7 @@ function Install-Gdn { $ci = $true . $PSScriptRoot\..\tools.ps1 - $argumentList = @("install", "Microsoft.Guardian.Cli.win-x64", "-Source $Source", "-OutputDirectory $Path", "-NonInteractive", "-NoCache") + $argumentList = @("install", "Microsoft.Guardian.Cli", "-Source https://securitytools.pkgs.visualstudio.com/_packaging/Guardian/nuget/v3/index.json", "-OutputDirectory $Path", "-NonInteractive", "-NoCache") if ($Version) { $argumentList += "-Version $Version" diff --git a/eng/common/sdl/trim-assets-version.ps1 b/eng/common/sdl/trim-assets-version.ps1 index a2e00487704..0daa2a9e946 100644 --- a/eng/common/sdl/trim-assets-version.ps1 +++ b/eng/common/sdl/trim-assets-version.ps1 @@ -72,4 +72,4 @@ catch { Write-Host $_ Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 -} \ No newline at end of file +} diff --git a/eng/common/template-guidance.md b/eng/common/template-guidance.md new file mode 100644 index 00000000000..5ef6c30ba92 --- /dev/null +++ b/eng/common/template-guidance.md @@ -0,0 +1,133 @@ +# Overview + +Arcade provides templates for public (`/templates`) and 1ES pipeline templates (`/templates-official`) scenarios. Pipelines which are required to be managed by 1ES pipeline templates should reference `/templates-offical`, all other pipelines may reference `/templates`. + +## How to use + +Basic guidance is: + +- 1ES Pipeline Template or 1ES Microbuild template runs should reference `eng/common/templates-official`. Any internal production-graded pipeline should use these templates. + +- All other runs should reference `eng/common/templates`. + +See [azure-pipelines.yml](../../azure-pipelines.yml) (templates-official example) or [azure-pipelines-pr.yml](../../azure-pipelines-pr.yml) (templates example) for examples. + +#### The `templateIs1ESManaged` parameter + +The `templateIs1ESManaged` is available on most templates and affects which of the variants is used for nested templates. See [Development Notes](#development-notes) below for more information on the `templateIs1ESManaged1 parameter. + +- For templates under `job/`, `jobs/`, `steps`, or `post-build/`, this parameter must be explicitly set. + +## Multiple outputs + +1ES pipeline templates impose a policy where every publish artifact execution results in additional security scans being injected into your pipeline. When using `templates-official/jobs/jobs.yml`, Arcade reduces the number of additional security injections by gathering all publishing outputs into the [Build.ArtifactStagingDirectory](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services), and utilizing the [outputParentDirectory](https://eng.ms/docs/cloud-ai-platform/devdiv/one-engineering-system-1es/1es-docs/1es-pipeline-templates/features/outputs#multiple-outputs) feature of 1ES pipeline templates. When implementing your pipeline, if you ensure publish artifacts are located in the `$(Build.ArtifactStagingDirectory)`, and utilize the 1ES provided template context, then you can reduce the number of security scans for your pipeline. + +Example: +``` yaml +# azure-pipelines.yml +extends: + template: azure-pipelines/MicroBuild.1ES.Official.yml@MicroBuildTemplate + parameters: + stages: + - stage: build + jobs: + - template: /eng/common/templates-official/jobs/jobs.yml@self + parameters: + # 1ES makes use of outputs to reduce security task injection overhead + templateContext: + outputs: + - output: pipelineArtifact + displayName: 'Publish logs from source' + continueOnError: true + condition: always() + targetPath: $(Build.ArtifactStagingDirectory)/artifacts/log + artifactName: Logs + jobs: + - job: Windows + steps: + - script: echo "friendly neighborhood" > artifacts/marvel/spiderman.txt + # copy build outputs to artifact staging directory for publishing + - task: CopyFiles@2 + displayName: Gather build output + inputs: + SourceFolder: '$(Build.SourcesDirectory)/artifacts/marvel' + Contents: '**' + TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/marvel' +``` + +Note: Multiple outputs are ONLY applicable to 1ES PT publishing (only usable when referencing `templates-official`). + +# Development notes + +**Folder / file structure** + +``` text +eng\common\ + [templates || templates-official]\ + job\ + job.yml (shim + artifact publishing logic) + onelocbuild.yml (shim) + publish-build-assets.yml (shim) + source-build.yml (shim) + source-index-stage1.yml (shim) + jobs\ + codeql-build.yml (shim) + jobs.yml (shim) + source-build.yml (shim) + post-build\ + post-build.yml (shim) + common-variabls.yml (shim) + setup-maestro-vars.yml (shim) + steps\ + publish-build-artifacts.yml (logic) + publish-pipeline-artifacts.yml (logic) + component-governance.yml (shim) + generate-sbom.yml (shim) + publish-logs.yml (shim) + retain-build.yml (shim) + send-to-helix.yml (shim) + source-build.yml (shim) + variables\ + pool-providers.yml (logic + redirect) # templates/variables/pool-providers.yml will redirect to templates-official/variables/pool-providers.yml if you are running in the internal project + sdl-variables.yml (logic) + core-templates\ + job\ + job.yml (logic) + onelocbuild.yml (logic) + publish-build-assets.yml (logic) + source-build.yml (logic) + source-index-stage1.yml (logic) + jobs\ + codeql-build.yml (logic) + jobs.yml (logic) + source-build.yml (logic) + post-build\ + common-variabls.yml (logic) + post-build.yml (logic) + setup-maestro-vars.yml (logic) + steps\ + component-governance.yml (logic) + generate-sbom.yml (logic) + publish-build-artifacts.yml (redirect) + publish-logs.yml (logic) + publish-pipeline-artifacts.yml (redirect) + retain-build.yml (logic) + send-to-helix.yml (logic) + source-build.yml (logic) + variables\ + pool-providers.yml (redirect) +``` + +In the table above, a file is designated as "shim", "logic", or "redirect". + +- shim - represents a yaml file which is an intermediate step between pipeline logic and .Net Core Engineering's templates (`core-templates`) and defines the `is1ESPipeline` parameter value. + +- logic - represents actual base template logic. + +- redirect- represents a file in `core-templates` which redirects to the "logic" file in either `templates` or `templates-official`. + +Logic for Arcade's templates live **primarily** in the `core-templates` folder. The exceptions to the location of the logic files are around artifact publishing, which is handled differently between 1es pipeline templates and standard templates. `templates` and `templates-official` provide shim entry points which redirect to `core-templates` while also defining the `is1ESPipeline` parameter. If a shim is referenced in `templates`, then `is1ESPipeline` is set to `false`. If a shim is referenced in `templates-official`, then `is1ESPipeline` is set to `true`. + +Within `templates` and `templates-official`, the templates at the "stages", and "jobs" / "job" level have been replaced with shims. Templates at the "steps" and "variables" level are typically too granular to be replaced with shims and instead persist logic which is directly applicable to either scenario. + +Within `core-templates`, there are a handful of places where logic is dependent on which shim entry point was used. In those places, we redirect back to the respective logic file in `templates` or `templates-official`. diff --git a/eng/common/templates-official/job/job.yml b/eng/common/templates-official/job/job.yml index 1f035fee73f..0c2928d5c79 100644 --- a/eng/common/templates-official/job/job.yml +++ b/eng/common/templates-official/job/job.yml @@ -1,264 +1,65 @@ -# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, -# and some (Microbuild) should only be applied to non-PR cases for internal builds. - -parameters: -# Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - cancelTimeoutInMinutes: '' - condition: '' - container: '' - continueOnError: false - dependsOn: '' - displayName: '' - pool: '' - steps: [] - strategy: '' - timeoutInMinutes: '' - variables: [] - workspace: '' - templateContext: '' - -# Job base template specific parameters - # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md - artifacts: '' - enableMicrobuild: false - enablePublishBuildArtifacts: false - enablePublishBuildAssets: false - enablePublishTestResults: false - enablePublishUsingPipelines: false - enableBuildRetry: false - disableComponentGovernance: '' - componentGovernanceIgnoreDirectories: '' - mergeTestResults: false - testRunTitle: '' - testResultsFormat: '' - name: '' - preSteps: [] - runAsPublic: false -# Sbom related params - enableSbom: true - PackageVersion: 7.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' - jobs: -- job: ${{ parameters.name }} - - ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: - cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} - - ${{ if ne(parameters.condition, '') }}: - condition: ${{ parameters.condition }} - - ${{ if ne(parameters.container, '') }}: - container: ${{ parameters.container }} - - ${{ if ne(parameters.continueOnError, '') }}: - continueOnError: ${{ parameters.continueOnError }} - - ${{ if ne(parameters.dependsOn, '') }}: - dependsOn: ${{ parameters.dependsOn }} - - ${{ if ne(parameters.displayName, '') }}: - displayName: ${{ parameters.displayName }} - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - - ${{ if ne(parameters.strategy, '') }}: - strategy: ${{ parameters.strategy }} - - ${{ if ne(parameters.timeoutInMinutes, '') }}: - timeoutInMinutes: ${{ parameters.timeoutInMinutes }} - - ${{ if ne(parameters.templateContext, '') }}: - templateContext: ${{ parameters.templateContext }} - - variables: - - ${{ if ne(parameters.enableTelemetry, 'false') }}: - - name: DOTNET_CLI_TELEMETRY_PROFILE - value: '$(Build.Repository.Uri)' - - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - - name: EnableRichCodeNavigation - value: 'true' - # Retry signature validation up to three times, waiting 2 seconds between attempts. - # See https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu3028#retry-untrusted-root-failures - - name: NUGET_EXPERIMENTAL_CHAIN_BUILD_RETRY_POLICY - value: 3,2000 - - ${{ each variable in parameters.variables }}: - # handle name-value variable syntax - # example: - # - name: [key] - # value: [value] - - ${{ if ne(variable.name, '') }}: - - name: ${{ variable.name }} - value: ${{ variable.value }} - - # handle variable groups - - ${{ if ne(variable.group, '') }}: - - group: ${{ variable.group }} - - # handle template variable syntax - # example: - # - template: path/to/template.yml - # parameters: - # [key]: [value] - - ${{ if ne(variable.template, '') }}: - - template: ${{ variable.template }} - ${{ if ne(variable.parameters, '') }}: - parameters: ${{ variable.parameters }} - - # handle key-value variable syntax. - # example: - # - [key]: [value] - - ${{ if and(eq(variable.name, ''), eq(variable.group, ''), eq(variable.template, '')) }}: - - ${{ each pair in variable }}: - - name: ${{ pair.key }} - value: ${{ pair.value }} - - # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - group: DotNet-HelixApi-Access - - ${{ if ne(parameters.workspace, '') }}: - workspace: ${{ parameters.workspace }} - - steps: - - ${{ if ne(parameters.preSteps, '') }}: - - ${{ each preStep in parameters.preSteps }}: - - ${{ preStep }} - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - task: MicroBuildSigningPlugin@4 - displayName: Install MicroBuild plugin - inputs: - signType: $(_SignType) - zipSources: false - feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json - env: - TeamName: $(_TeamName) - MicroBuildOutputFolderOverride: '$(Agent.TempDirectory)' - continueOnError: ${{ parameters.continueOnError }} - condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - - - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: - - task: NuGetAuthenticate@1 - - - ${{ if and(ne(parameters.artifacts.download, 'false'), ne(parameters.artifacts.download, '')) }}: - - task: DownloadPipelineArtifact@2 - inputs: - buildType: current - artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} - targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} - itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - - - ${{ each step in parameters.steps }}: - - ${{ step }} - - - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - - task: RichCodeNavIndexer@0 - displayName: RichCodeNav Upload - inputs: - languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} - environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} - richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin - uploadRichNavArtifacts: ${{ coalesce(parameters.richCodeNavigationUploadArtifacts, false) }} - continueOnError: true - - - template: /eng/common/templates-official/steps/component-governance.yml - parameters: - ${{ if eq(parameters.disableComponentGovernance, '') }}: - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/dotnet/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/microsoft/'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))) }}: - disableComponentGovernance: false - ${{ else }}: - disableComponentGovernance: true - ${{ else }}: - disableComponentGovernance: ${{ parameters.disableComponentGovernance }} - componentGovernanceIgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} - - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: MicroBuildCleanup@1 - displayName: Execute Microbuild cleanup tasks - condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} - env: - TeamName: $(_TeamName) - - - ${{ if ne(parameters.artifacts.publish, '') }}: - - ${{ if and(ne(parameters.artifacts.publish.artifacts, 'false'), ne(parameters.artifacts.publish.artifacts, '')) }}: - - task: CopyFiles@2 - displayName: Gather binaries for publish to artifacts - inputs: - SourceFolder: 'artifacts/bin' - Contents: '**' - TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - - task: CopyFiles@2 - displayName: Gather packages for publish to artifacts - inputs: - SourceFolder: 'artifacts/packages' - Contents: '**' - TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish pipeline artifacts - inputs: - PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' - PublishLocation: Container - ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} - continueOnError: true - condition: always() - - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: - - task: 1ES.PublishPipelineArtifact@1 - inputs: - targetPath: 'artifacts/log' - artifactName: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} - displayName: 'Publish logs' - continueOnError: true - condition: always() - - - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish Logs - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' - PublishLocation: Container - ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} - continueOnError: true - condition: always() - - - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - - task: PublishTestResults@2 - displayName: Publish XUnit Test Results - inputs: - testResultsFormat: 'xUnit' - testResultsFiles: '*.xml' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit - mergeTestResults: ${{ parameters.mergeTestResults }} - continueOnError: true - condition: always() - - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - - task: PublishTestResults@2 - displayName: Publish TRX Test Results - inputs: - testResultsFormat: 'VSTest' - testResultsFiles: '*.trx' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx - mergeTestResults: ${{ parameters.mergeTestResults }} - continueOnError: true - condition: always() - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: - - template: /eng/common/templates-official/steps/generate-sbom.yml - parameters: - PackageVersion: ${{ parameters.packageVersion}} - BuildDropPath: ${{ parameters.buildDropPath }} - IgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} - - - ${{ if eq(parameters.enableBuildRetry, 'true') }}: - - task: 1ES.PublishPipelineArtifact@1 - inputs: - targetPath: '$(Build.SourcesDirectory)\eng\common\BuildConfiguration' - artifactName: 'BuildConfiguration' - displayName: 'Publish build retry configuration' - continueOnError: true \ No newline at end of file +- template: /eng/common/core-templates/job/job.yml + parameters: + is1ESPipeline: true + + # publish artifacts + # for 1ES managed templates, use the templateContext.output to handle multiple outputs. + templateContext: + outputParentDirectory: $(Build.ArtifactStagingDirectory) + outputs: + - ${{ if ne(parameters.artifacts.publish, '') }}: + - ${{ if and(ne(parameters.artifacts.publish.artifacts, 'false'), ne(parameters.artifacts.publish.artifacts, '')) }}: + - output: buildArtifacts + displayName: Publish pipeline artifacts + PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' + ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} + condition: always() + continueOnError: true + - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: + - output: pipelineArtifact + targetPath: '$(Build.ArtifactStagingDirectory)/artifacts/log' + artifactName: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)_Attempt$(System.JobAttempt)') }} + displayName: 'Publish logs' + continueOnError: true + condition: always() + sbomEnabled: false # we don't need SBOM for logs + + - ${{ if eq(parameters.enablePublishBuildArtifacts, true) }}: + - output: buildArtifacts + displayName: Publish Logs + PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts/log/$(_BuildConfig)' + publishLocation: Container + ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} + continueOnError: true + condition: always() + sbomEnabled: false # we don't need SBOM for logs + + - ${{ if eq(parameters.enableBuildRetry, 'true') }}: + - output: pipelineArtifact + targetPath: '$(Build.ArtifactStagingDirectory)/artifacts/eng/common/BuildConfiguration' + artifactName: 'BuildConfiguration' + displayName: 'Publish build retry configuration' + continueOnError: true + sbomEnabled: false # we don't need SBOM for BuildConfiguration + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: + - output: pipelineArtifact + displayName: Publish SBOM manifest + continueOnError: true + targetPath: $(Build.ArtifactStagingDirectory)/sbom + artifactName: $(ARTIFACT_NAME) + + # add any outputs provided via root yaml + - ${{ if ne(parameters.templateContext.outputs, '') }}: + - ${{ each output in parameters.templateContext.outputs }}: + - ${{ output }} + + # add any remaining templateContext properties + ${{ each context in parameters.templateContext }}: + ${{ if and(ne(context.key, 'outputParentDirectory'), ne(context.key, 'outputs')) }}: + ${{ context.key }}: ${{ context.value }} + + ${{ each parameter in parameters }}: + ${{ if and(ne(parameter.key, 'templateContext'), ne(parameter.key, 'is1ESPipeline')) }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/job/onelocbuild.yml b/eng/common/templates-official/job/onelocbuild.yml index 52b4d05d3f8..0f0c514b912 100644 --- a/eng/common/templates-official/job/onelocbuild.yml +++ b/eng/common/templates-official/job/onelocbuild.yml @@ -1,112 +1,7 @@ -parameters: - # Optional: dependencies of the job - dependsOn: '' - - # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool - pool: '' - - CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex - GithubPat: $(BotAccount-dotnet-bot-repo-PAT) - - SourcesDirectory: $(Build.SourcesDirectory) - CreatePr: true - AutoCompletePr: false - ReusePr: true - UseLfLineEndings: true - UseCheckedInLocProjectJson: false - SkipLocProjectJsonGeneration: false - LanguageSet: VS_Main_Languages - LclSource: lclFilesInRepo - LclPackageId: '' - RepoType: gitHub - GitHubOrg: dotnet - MirrorRepo: '' - MirrorBranch: main - condition: '' - JobNameSuffix: '' - jobs: -- job: OneLocBuild${{ parameters.JobNameSuffix }} - - dependsOn: ${{ parameters.dependsOn }} - - displayName: OneLocBuild${{ parameters.JobNameSuffix }} - - variables: - - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - - name: _GenerateLocProjectArguments - value: -SourcesDirectory ${{ parameters.SourcesDirectory }} - -LanguageSet "${{ parameters.LanguageSet }}" - -CreateNeutralXlfs - - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - - name: _GenerateLocProjectArguments - value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson - - template: /eng/common/templates-official/variables/pool-providers.yml - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - ${{ if eq(parameters.pool, '') }}: - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: - name: $(DncEngInternalBuildPool) - image: 1es-windows-2022 - os: windows - - steps: - - ${{ if ne(parameters.SkipLocProjectJsonGeneration, 'true') }}: - - task: Powershell@2 - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 - arguments: $(_GenerateLocProjectArguments) - displayName: Generate LocProject.json - condition: ${{ parameters.condition }} - - - task: OneLocBuild@2 - displayName: OneLocBuild - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - locProj: eng/Localize/LocProject.json - outDir: $(Build.ArtifactStagingDirectory) - lclSource: ${{ parameters.LclSource }} - lclPackageId: ${{ parameters.LclPackageId }} - isCreatePrSelected: ${{ parameters.CreatePr }} - isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} - ${{ if eq(parameters.CreatePr, true) }}: - isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - isShouldReusePrSelected: ${{ parameters.ReusePr }} - packageSourceAuth: patAuth - patVariable: ${{ parameters.CeapexPat }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - repoType: ${{ parameters.RepoType }} - gitHubPatVariable: "${{ parameters.GithubPat }}" - ${{ if ne(parameters.MirrorRepo, '') }}: - isMirrorRepoSelected: true - gitHubOrganization: ${{ parameters.GitHubOrg }} - mirrorRepo: ${{ parameters.MirrorRepo }} - mirrorBranch: ${{ parameters.MirrorBranch }} - condition: ${{ parameters.condition }} - - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish Localization Files - inputs: - PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' - PublishLocation: Container - ArtifactName: Loc - condition: ${{ parameters.condition }} +- template: /eng/common/core-templates/job/onelocbuild.yml + parameters: + is1ESPipeline: true - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish LocProject.json - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' - PublishLocation: Container - ArtifactName: Loc - condition: ${{ parameters.condition }} \ No newline at end of file + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/job/publish-build-assets.yml b/eng/common/templates-official/job/publish-build-assets.yml index 0117328800c..d667a70e8de 100644 --- a/eng/common/templates-official/job/publish-build-assets.yml +++ b/eng/common/templates-official/job/publish-build-assets.yml @@ -1,160 +1,7 @@ -parameters: - configuration: 'Debug' - - # Optional: condition for the job to run - condition: '' - - # Optional: 'true' if future jobs should run even if this job fails - continueOnError: false - - # Optional: dependencies of the job - dependsOn: '' - - # Optional: Include PublishBuildArtifacts task - enablePublishBuildArtifacts: false - - # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool - pool: {} - - # Optional: should run as a public build even in the internal project - # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. - runAsPublic: false - - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing - publishUsingPipelines: false - - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing - publishAssetsImmediately: false - - artifactsPublishingAdditionalParameters: '' - - signingValidationAdditionalParameters: '' - jobs: -- job: Asset_Registry_Publish - - dependsOn: ${{ parameters.dependsOn }} - timeoutInMinutes: 150 - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - displayName: Publish Assets - ${{ else }}: - displayName: Publish to Build Asset Registry - - variables: - - template: /eng/common/templates-official/variables/pool-providers.yml - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - group: Publish-Build-Assets - - group: AzureDevOps-Artifact-Feeds-Pats - - name: runCodesignValidationInjection - value: false - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - - template: /eng/common/templates-official/post-build/common-variables.yml - - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: - name: NetCore1ESPool-Publishing-Internal - image: windows.vs2019.amd64 - os: windows - steps: - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: DownloadBuildArtifacts@0 - displayName: Download artifact - inputs: - artifactName: AssetManifests - downloadPath: '$(Build.StagingDirectory)/Download' - checkDownloadedFiles: true - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} - - - task: NuGetAuthenticate@1 - - - task: AzureCLI@2 - displayName: Publish Build Assets - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 - arguments: > - -task PublishBuildAssets -restore -msbuildEngine dotnet - /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' - /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com - /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} - /p:OfficialBuildId=$(Build.BuildNumber) - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} - - - task: powershell@2 - displayName: Create ReleaseConfigs Artifact - inputs: - targetType: inline - script: | - New-Item -Path "$(Build.StagingDirectory)/ReleaseConfigs" -ItemType Directory -Force - $filePath = "$(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt" - Add-Content -Path $filePath -Value $(BARBuildId) - Add-Content -Path $filePath -Value "$(DefaultChannels)" - Add-Content -Path $filePath -Value $(IsStableBuild) - - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish ReleaseConfigs Artifact - inputs: - PathtoPublish: '$(Build.StagingDirectory)/ReleaseConfigs' - PublishLocation: Container - ArtifactName: ReleaseConfigs - - - task: powershell@2 - displayName: Check if SymbolPublishingExclusionsFile.txt exists - inputs: - targetType: inline - script: | - $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" - if(Test-Path -Path $symbolExclusionfile) - { - Write-Host "SymbolExclusionFile exists" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]true" - } - else{ - Write-Host "Symbols Exclusion file does not exists" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]false" - } - - - task: 1ES.PublishBuildArtifacts@1 - displayName: Publish SymbolPublishingExclusionsFile Artifact - condition: eq(variables['SymbolExclusionFile'], 'true') - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' - PublishLocation: Container - ArtifactName: ReleaseConfigs - - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - - template: /eng/common/templates-official/post-build/setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: AzureCLI@2 - displayName: Publish Using Darc - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) - -PublishingInfraVersion 3 - -AzdoToken '$(System.AccessToken)' - -WaitPublishingFinish true - -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' - -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' +- template: /eng/common/core-templates/job/publish-build-assets.yml + parameters: + is1ESPipeline: true - - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - - template: /eng/common/templates-official/steps/publish-logs.yml - parameters: - JobLabel: 'Publish_Artifacts_Logs' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/job/source-build.yml b/eng/common/templates-official/job/source-build.yml index f983033bb02..1a480034b67 100644 --- a/eng/common/templates-official/job/source-build.yml +++ b/eng/common/templates-official/job/source-build.yml @@ -1,75 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. The template produces a server job with a - # default ID 'Source_Build_Complete' to put in a dependency list if necessary. - - # Specifies the prefix for source-build jobs added to pipeline. Use this if disambiguation needed. - jobNamePrefix: 'Source_Build' - - # Defines the platform on which to run the job. By default, a linux-x64 machine, suitable for - # managed-only repositories. This is an object with these properties: - # - # name: '' - # The name of the job. This is included in the job ID. - # targetRID: '' - # The name of the target RID to use, instead of the one auto-detected by Arcade. - # nonPortable: false - # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than - # linux-x64), and compiling against distro-provided packages rather than portable ones. - # skipPublishValidation: false - # Disables publishing validation. By default, a check is performed to ensure no packages are - # published by source-build. - # container: '' - # A container to use. Runs in docker. - # pool: {} - # A pool to use. Runs directly on an agent. - # buildScript: '' - # Specifies the build script to invoke to perform the build in the repo. The default - # './build.sh' should work for typical Arcade repositories, but this is customizable for - # difficult situations. - # jobProperties: {} - # A list of job properties to inject at the top level, for potential extensibility beyond - # container and pool. - platform: {} - - # If set to true and running on a non-public project, - # Internal blob storage locations will be enabled. - # This is not enabled by default because many repositories do not need internal sources - # and do not need to have the required service connections approved in the pipeline. - enableInternalSources: false - jobs: -- job: ${{ parameters.jobNamePrefix }}_${{ parameters.platform.name }} - displayName: Source-Build (${{ parameters.platform.name }}) - - ${{ each property in parameters.platform.jobProperties }}: - ${{ property.key }}: ${{ property.value }} - - ${{ if ne(parameters.platform.container, '') }}: - container: ${{ parameters.platform.container }} - - ${{ if eq(parameters.platform.pool, '') }}: - # The default VM host AzDO pool. This should be capable of running Docker containers: almost all - # source-build builds run in Docker, including the default managed platform. - # /eng/common/templates-official/variables/pool-providers.yml can't be used here (some customers declare variables already), so duplicate its logic - pool: - ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore-Svc-Public' ), False, 'NetCore-Public')] - demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open - - ${{ if eq(variables['System.TeamProject'], 'internal') }}: - name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore1ESPool-Svc-Internal'), False, 'NetCore1ESPool-Internal')] - image: 1es-mariner-2 - os: linux - - ${{ if ne(parameters.platform.pool, '') }}: - pool: ${{ parameters.platform.pool }} - - workspace: - clean: all +- template: /eng/common/core-templates/job/source-build.yml + parameters: + is1ESPipeline: true - steps: - - ${{ if eq(parameters.enableInternalSources, true) }}: - - template: /eng/common/templates-official/steps/enable-internal-runtimes.yml - - template: /eng/common/templates-official/steps/source-build.yml - parameters: - platform: ${{ parameters.platform }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/job/source-index-stage1.yml b/eng/common/templates-official/job/source-index-stage1.yml index 60dfb6b2d1c..6d5ead316f9 100644 --- a/eng/common/templates-official/job/source-index-stage1.yml +++ b/eng/common/templates-official/job/source-index-stage1.yml @@ -1,83 +1,7 @@ -parameters: - runAsPublic: false - sourceIndexUploadPackageVersion: 2.0.0-20240502.12 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20240129.2 - sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json - sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" - preSteps: [] - binlogPath: artifacts/log/Debug/Build.binlog - condition: '' - dependsOn: '' - pool: '' - jobs: -- job: SourceIndexStage1 - dependsOn: ${{ parameters.dependsOn }} - condition: ${{ parameters.condition }} - variables: - - name: SourceIndexUploadPackageVersion - value: ${{ parameters.sourceIndexUploadPackageVersion }} - - name: SourceIndexProcessBinlogPackageVersion - value: ${{ parameters.sourceIndexProcessBinlogPackageVersion }} - - name: SourceIndexPackageSource - value: ${{ parameters.sourceIndexPackageSource }} - - name: BinlogPath - value: ${{ parameters.binlogPath }} - - template: /eng/common/templates-official/variables/pool-providers.yml - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - ${{ if eq(parameters.pool, '') }}: - pool: - ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: $(DncEngPublicBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64.open - ${{ if eq(variables['System.TeamProject'], 'internal') }}: - name: $(DncEngInternalBuildPool) - image: windows.vs2022.amd64 - os: windows - - steps: - - ${{ each preStep in parameters.preSteps }}: - - ${{ preStep }} - - - task: UseDotNet@2 - displayName: Use .NET 8 SDK - inputs: - packageType: sdk - version: 8.0.x - installationPath: $(Agent.TempDirectory)/dotnet - workingDirectory: $(Agent.TempDirectory) - - - script: | - $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version $(sourceIndexProcessBinlogPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version $(sourceIndexUploadPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - displayName: Download Tools - # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. - workingDirectory: $(Agent.TempDirectory) - - - script: ${{ parameters.sourceIndexBuildCommand }} - displayName: Build Repository - - - script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output - displayName: Process Binlog into indexable sln - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: AzureCLI@2 - displayName: Get stage 1 auth token - inputs: - azureSubscription: 'SourceDotNet Stage1 Publish' - addSpnToEnvironment: true - scriptType: 'ps' - scriptLocation: 'inlineScript' - inlineScript: | - echo "##vso[task.setvariable variable=ARM_CLIENT_ID;issecret=true]$env:servicePrincipalId" - echo "##vso[task.setvariable variable=ARM_ID_TOKEN;issecret=true]$env:idToken" - echo "##vso[task.setvariable variable=ARM_TENANT_ID;issecret=true]$env:tenantId" - - - script: | - az login --service-principal -u $(ARM_CLIENT_ID) --tenant $(ARM_TENANT_ID) --allow-no-subscriptions --federated-token $(ARM_ID_TOKEN) - displayName: "Login to Azure" +- template: /eng/common/core-templates/job/source-index-stage1.yml + parameters: + is1ESPipeline: true - - script: $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 - displayName: Upload stage1 artifacts to source index + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/jobs/codeql-build.yml b/eng/common/templates-official/jobs/codeql-build.yml index b68d3c2f319..a726322ecfe 100644 --- a/eng/common/templates-official/jobs/codeql-build.yml +++ b/eng/common/templates-official/jobs/codeql-build.yml @@ -1,31 +1,7 @@ -parameters: - # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md - continueOnError: false - # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - jobs: [] - # Optional: if specified, restore and use this version of Guardian instead of the default. - overrideGuardianVersion: '' - jobs: -- template: /eng/common/templates-official/jobs/jobs.yml +- template: /eng/common/core-templates/jobs/codeql-build.yml parameters: - enableMicrobuild: false - enablePublishBuildArtifacts: false - enablePublishTestResults: false - enablePublishBuildAssets: false - enablePublishUsingPipelines: false - enableTelemetry: true + is1ESPipeline: true - variables: - - group: Publish-Build-Assets - # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in - # sync with the packages.config file. - - name: DefaultGuardianVersion - value: 0.109.0 - - name: GuardianPackagesConfigFile - value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config - - name: GuardianVersion - value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} - - jobs: ${{ parameters.jobs }} - + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/jobs/jobs.yml b/eng/common/templates-official/jobs/jobs.yml index 857a0f8ba43..007deddaea0 100644 --- a/eng/common/templates-official/jobs/jobs.yml +++ b/eng/common/templates-official/jobs/jobs.yml @@ -1,97 +1,7 @@ -parameters: - # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md - continueOnError: false - - # Optional: Include PublishBuildArtifacts task - enablePublishBuildArtifacts: false - - # Optional: Enable publishing using release pipelines - enablePublishUsingPipelines: false - - # Optional: Enable running the source-build jobs to build repo from source - enableSourceBuild: false - - # Optional: Parameters for source-build template. - # See /eng/common/templates-official/jobs/source-build.yml for options - sourceBuildParameters: [] - - graphFileGeneration: - # Optional: Enable generating the graph files at the end of the build - enabled: false - # Optional: Include toolset dependencies in the generated graph files - includeToolset: false - - # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - jobs: [] - - # Optional: Override automatically derived dependsOn value for "publish build assets" job - publishBuildAssetsDependsOn: '' - - # Optional: Publish the assets as soon as the publish to BAR stage is complete, rather doing so in a separate stage. - publishAssetsImmediately: false - - # Optional: If using publishAssetsImmediately and additional parameters are needed, can be used to send along additional parameters (normally sent to post-build.yml) - artifactsPublishingAdditionalParameters: '' - signingValidationAdditionalParameters: '' - - # Optional: should run as a public build even in the internal project - # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. - runAsPublic: false - - enableSourceIndex: false - sourceIndexParams: {} - -# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, -# and some (Microbuild) should only be applied to non-PR cases for internal builds. - jobs: -- ${{ each job in parameters.jobs }}: - - template: ../job/job.yml - parameters: - # pass along parameters - ${{ each parameter in parameters }}: - ${{ if ne(parameter.key, 'jobs') }}: - ${{ parameter.key }}: ${{ parameter.value }} - - # pass along job properties - ${{ each property in job }}: - ${{ if ne(property.key, 'job') }}: - ${{ property.key }}: ${{ property.value }} - - name: ${{ job.job }} - -- ${{ if eq(parameters.enableSourceBuild, true) }}: - - template: /eng/common/templates-official/jobs/source-build.yml - parameters: - allCompletedJobId: Source_Build_Complete - ${{ each parameter in parameters.sourceBuildParameters }}: - ${{ parameter.key }}: ${{ parameter.value }} - -- ${{ if eq(parameters.enableSourceIndex, 'true') }}: - - template: ../job/source-index-stage1.yml - parameters: - runAsPublic: ${{ parameters.runAsPublic }} - ${{ each parameter in parameters.sourceIndexParams }}: - ${{ parameter.key }}: ${{ parameter.value }} - -- ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if or(eq(parameters.enablePublishBuildAssets, true), eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - - template: ../job/publish-build-assets.yml - parameters: - continueOnError: ${{ parameters.continueOnError }} - dependsOn: - - ${{ if ne(parameters.publishBuildAssetsDependsOn, '') }}: - - ${{ each job in parameters.publishBuildAssetsDependsOn }}: - - ${{ job.job }} - - ${{ if eq(parameters.publishBuildAssetsDependsOn, '') }}: - - ${{ each job in parameters.jobs }}: - - ${{ job.job }} - - ${{ if eq(parameters.enableSourceBuild, true) }}: - - Source_Build_Complete +- template: /eng/common/core-templates/jobs/jobs.yml + parameters: + is1ESPipeline: true - runAsPublic: ${{ parameters.runAsPublic }} - publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} - publishAssetsImmediately: ${{ parameters.publishAssetsImmediately }} - enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/jobs/source-build.yml b/eng/common/templates-official/jobs/source-build.yml index 5cf6a269c0b..483e7b611f3 100644 --- a/eng/common/templates-official/jobs/source-build.yml +++ b/eng/common/templates-official/jobs/source-build.yml @@ -1,54 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. A job is created for each platform, as - # well as an optional server job that completes when all platform jobs complete. - - # The name of the "join" job for all source-build platforms. If set to empty string, the job is - # not included. Existing repo pipelines can use this job depend on all source-build jobs - # completing without maintaining a separate list of every single job ID: just depend on this one - # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. - allCompletedJobId: '' - - # See /eng/common/templates-official/job/source-build.yml - jobNamePrefix: 'Source_Build' - - # This is the default platform provided by Arcade, intended for use by a managed-only repo. - defaultManagedPlatform: - name: 'Managed' - container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream8' - - # Defines the platforms on which to run build jobs. One job is created for each platform, and the - # object in this array is sent to the job template as 'platform'. If no platforms are specified, - # one job runs on 'defaultManagedPlatform'. - platforms: [] - - # If set to true and running on a non-public project, - # Internal nuget and blob storage locations will be enabled. - # This is not enabled by default because many repositories do not need internal sources - # and do not need to have the required service connections approved in the pipeline. - enableInternalSources: false - jobs: +- template: /eng/common/core-templates/jobs/source-build.yml + parameters: + is1ESPipeline: true -- ${{ if ne(parameters.allCompletedJobId, '') }}: - - job: ${{ parameters.allCompletedJobId }} - displayName: Source-Build Complete - pool: server - dependsOn: - - ${{ each platform in parameters.platforms }}: - - ${{ parameters.jobNamePrefix }}_${{ platform.name }} - - ${{ if eq(length(parameters.platforms), 0) }}: - - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} - -- ${{ each platform in parameters.platforms }}: - - template: /eng/common/templates-official/job/source-build.yml - parameters: - jobNamePrefix: ${{ parameters.jobNamePrefix }} - platform: ${{ platform }} - enableInternalSources: ${{ parameters.enableInternalSources }} - -- ${{ if eq(length(parameters.platforms), 0) }}: - - template: /eng/common/templates-official/job/source-build.yml - parameters: - jobNamePrefix: ${{ parameters.jobNamePrefix }} - platform: ${{ parameters.defaultManagedPlatform }} - enableInternalSources: ${{ parameters.enableInternalSources }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/post-build/common-variables.yml b/eng/common/templates-official/post-build/common-variables.yml index c24193acfc9..c32fc49233f 100644 --- a/eng/common/templates-official/post-build/common-variables.yml +++ b/eng/common/templates-official/post-build/common-variables.yml @@ -1,22 +1,8 @@ variables: - - group: Publish-Build-Assets +- template: /eng/common/core-templates/post-build/common-variables.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: true - # Whether the build is internal or not - - name: IsInternalBuild - value: ${{ and(ne(variables['System.TeamProject'], 'public'), contains(variables['Build.SourceBranch'], 'internal')) }} - - # Default Maestro++ API Endpoint and API Version - - name: MaestroApiEndPoint - value: "https://maestro-prod.westus2.cloudapp.azure.com" - - name: MaestroApiAccessToken - value: $(MaestroAccessToken) - - name: MaestroApiVersion - value: "2020-02-20" - - - name: SourceLinkCLIVersion - value: 3.0.0 - - name: SymbolToolVersion - value: 1.0.1 - - - name: runCodesignValidationInjection - value: false + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/post-build/post-build.yml b/eng/common/templates-official/post-build/post-build.yml index b81b8770b34..2364c0fd4a5 100644 --- a/eng/common/templates-official/post-build/post-build.yml +++ b/eng/common/templates-official/post-build/post-build.yml @@ -1,287 +1,8 @@ -parameters: - # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST. - # Publishing V1 is no longer supported - # Publishing V2 is no longer supported - # Publishing V3 is the default - - name: publishingInfraVersion - displayName: Which version of publishing should be used to promote the build definition? - type: number - default: 3 - values: - - 3 - - - name: BARBuildId - displayName: BAR Build Id - type: number - default: 0 - - - name: PromoteToChannelIds - displayName: Channel to promote BARBuildId to - type: string - default: '' - - - name: enableSourceLinkValidation - displayName: Enable SourceLink validation - type: boolean - default: false - - - name: enableSigningValidation - displayName: Enable signing validation - type: boolean - default: true - - - name: enableSymbolValidation - displayName: Enable symbol validation - type: boolean - default: false - - - name: enableNugetValidation - displayName: Enable NuGet validation - type: boolean - default: true - - - name: publishInstallersAndChecksums - displayName: Publish installers and checksums - type: boolean - default: true - - - name: SDLValidationParameters - type: object - default: - enable: false - publishGdn: false - continueOnError: false - params: '' - artifactNames: '' - downloadArtifacts: true - - # These parameters let the user customize the call to sdk-task.ps1 for publishing - # symbols & general artifacts as well as for signing validation - - name: symbolPublishingAdditionalParameters - displayName: Symbol publishing additional parameters - type: string - default: '' - - - name: artifactsPublishingAdditionalParameters - displayName: Artifact publishing additional parameters - type: string - default: '' - - - name: signingValidationAdditionalParameters - displayName: Signing validation additional parameters - type: string - default: '' - - # Which stages should finish execution before post-build stages start - - name: validateDependsOn - type: object - default: - - build - - - name: publishDependsOn - type: object - default: - - Validate - - # Optional: Call asset publishing rather than running in a separate stage - - name: publishAssetsImmediately - type: boolean - default: false - stages: -- ${{ if or(eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - - stage: Validate - dependsOn: ${{ parameters.validateDependsOn }} - displayName: Validate Build Assets - variables: - - template: common-variables.yml - - template: /eng/common/templates-official/variables/pool-providers.yml - jobs: - - job: - displayName: NuGet Validation - condition: and(succeededOrFailed(), eq( ${{ parameters.enableNugetValidation }}, 'true')) - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - image: 1es-windows-2022 - os: windows - - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Package Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: PackageArtifacts - checkDownloadedFiles: true - - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/nuget-validation.ps1 - arguments: -PackagesPath $(Build.ArtifactStagingDirectory)/PackageArtifacts/ - -ToolDestinationPath $(Agent.BuildDirectory)/Extract/ - - - job: - displayName: Signing Validation - condition: and( eq( ${{ parameters.enableSigningValidation }}, 'true'), ne( variables['PostBuildSign'], 'true')) - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - image: 1es-windows-2022 - os: windows - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Package Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: PackageArtifacts - checkDownloadedFiles: true - itemPattern: | - ** - !**/Microsoft.SourceBuild.Intermediate.*.nupkg - - # This is necessary whenever we want to publish/restore to an AzDO private feed - # Since sdk-task.ps1 tries to restore packages we need to do this authentication here - # otherwise it'll complain about accessing a private feed. - - task: NuGetAuthenticate@1 - displayName: 'Authenticate to AzDO Feeds' - - # Signing validation will optionally work with the buildmanifest file which is downloaded from - # Azure DevOps above. - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task SigningValidation -restore -msbuildEngine vs - /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts' - /p:SignCheckExclusionsFile='$(Build.SourcesDirectory)/eng/SignCheckExclusionsFile.txt' - ${{ parameters.signingValidationAdditionalParameters }} - - - template: ../steps/publish-logs.yml - parameters: - StageLabel: 'Validation' - JobLabel: 'Signing' - BinlogToolVersion: $(BinlogToolVersion) - - - job: - displayName: SourceLink Validation - condition: eq( ${{ parameters.enableSourceLinkValidation }}, 'true') - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - image: 1es-windows-2022 - os: windows - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Blob Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: BlobArtifacts - checkDownloadedFiles: true - - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/sourcelink-validation.ps1 - arguments: -InputPath $(Build.ArtifactStagingDirectory)/BlobArtifacts/ - -ExtractPath $(Agent.BuildDirectory)/Extract/ - -GHRepoName $(Build.Repository.Name) - -GHCommit $(Build.SourceVersion) - -SourcelinkCliVersion $(SourceLinkCLIVersion) - continueOnError: true - -- ${{ if ne(parameters.publishAssetsImmediately, 'true') }}: - - stage: publish_using_darc - ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - dependsOn: ${{ parameters.publishDependsOn }} - ${{ else }}: - dependsOn: ${{ parameters.validateDependsOn }} - displayName: Publish using Darc - variables: - - template: common-variables.yml - - template: /eng/common/templates-official/variables/pool-providers.yml - jobs: - - job: - displayName: Publish Using Darc - timeoutInMinutes: 120 - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: AzurePipelines-EO - image: 1ESPT-Windows2022 - demands: Cmd - os: windows - # If it's not devdiv, it's dnceng - ${{ else }}: - name: NetCore1ESPool-Publishing-Internal - image: windows.vs2019.amd64 - os: windows - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: NuGetAuthenticate@1 +- template: /eng/common/core-templates/post-build/post-build.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: true - - task: AzureCLI@2 - displayName: Publish Using Darc - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) - -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} - -AzdoToken '$(System.AccessToken)' - -WaitPublishingFinish true - -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' - -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/post-build/setup-maestro-vars.yml b/eng/common/templates-official/post-build/setup-maestro-vars.yml index 0c87f149a4a..024397d8786 100644 --- a/eng/common/templates-official/post-build/setup-maestro-vars.yml +++ b/eng/common/templates-official/post-build/setup-maestro-vars.yml @@ -1,70 +1,8 @@ -parameters: - BARBuildId: '' - PromoteToChannelIds: '' - steps: - - ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}: - - task: DownloadBuildArtifacts@0 - displayName: Download Release Configs - inputs: - buildType: current - artifactName: ReleaseConfigs - checkDownloadedFiles: true - - - task: PowerShell@2 - name: setReleaseVars - displayName: Set Release Configs Vars - inputs: - targetType: inline - pwsh: true - script: | - try { - if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { - $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt - - $BarId = $Content | Select -Index 0 - $Channels = $Content | Select -Index 1 - $IsStableBuild = $Content | Select -Index 2 - - $AzureDevOpsProject = $Env:System_TeamProject - $AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId - $AzureDevOpsBuildId = $Env:Build_BuildId - } - else { - $buildApiEndpoint = "${Env:MaestroApiEndPoint}/api/builds/${Env:BARBuildId}?api-version=${Env:MaestroApiVersion}" - - $apiHeaders = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' - $apiHeaders.Add('Accept', 'application/json') - $apiHeaders.Add('Authorization',"Bearer ${Env:MAESTRO_API_TOKEN}") - - $buildInfo = try { Invoke-WebRequest -Method Get -Uri $buildApiEndpoint -Headers $apiHeaders | ConvertFrom-Json } catch { Write-Host "Error: $_" } - - $BarId = $Env:BARBuildId - $Channels = $Env:PromoteToMaestroChannels -split "," - $Channels = $Channels -join "][" - $Channels = "[$Channels]" - - $IsStableBuild = $buildInfo.stable - $AzureDevOpsProject = $buildInfo.azureDevOpsProject - $AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId - $AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId - } - - Write-Host "##vso[task.setvariable variable=BARBuildId]$BarId" - Write-Host "##vso[task.setvariable variable=TargetChannels]$Channels" - Write-Host "##vso[task.setvariable variable=IsStableBuild]$IsStableBuild" +- template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: true - Write-Host "##vso[task.setvariable variable=AzDOProjectName]$AzureDevOpsProject" - Write-Host "##vso[task.setvariable variable=AzDOPipelineId]$AzureDevOpsBuildDefinitionId" - Write-Host "##vso[task.setvariable variable=AzDOBuildId]$AzureDevOpsBuildId" - } - catch { - Write-Host $_ - Write-Host $_.Exception - Write-Host $_.ScriptStackTrace - exit 1 - } - env: - MAESTRO_API_TOKEN: $(MaestroApiAccessToken) - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/post-build/trigger-subscription.yml b/eng/common/templates-official/post-build/trigger-subscription.yml deleted file mode 100644 index da669030daf..00000000000 --- a/eng/common/templates-official/post-build/trigger-subscription.yml +++ /dev/null @@ -1,13 +0,0 @@ -parameters: - ChannelId: 0 - -steps: -- task: PowerShell@2 - displayName: Triggering subscriptions - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/trigger-subscriptions.ps1 - arguments: -SourceRepo $(Build.Repository.Uri) - -ChannelId ${{ parameters.ChannelId }} - -MaestroApiAccessToken $(MaestroAccessToken) - -MaestroApiEndPoint $(MaestroApiEndPoint) - -MaestroApiVersion $(MaestroApiVersion) diff --git a/eng/common/templates-official/steps/add-build-to-channel.yml b/eng/common/templates-official/steps/add-build-to-channel.yml deleted file mode 100644 index f67a210d62f..00000000000 --- a/eng/common/templates-official/steps/add-build-to-channel.yml +++ /dev/null @@ -1,13 +0,0 @@ -parameters: - ChannelId: 0 - -steps: -- task: PowerShell@2 - displayName: Add Build to Channel - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/add-build-to-channel.ps1 - arguments: -BuildId $(BARBuildId) - -ChannelId ${{ parameters.ChannelId }} - -MaestroApiAccessToken $(MaestroApiAccessToken) - -MaestroApiEndPoint $(MaestroApiEndPoint) - -MaestroApiVersion $(MaestroApiVersion) diff --git a/eng/common/templates-official/steps/build-reason.yml b/eng/common/templates-official/steps/build-reason.yml deleted file mode 100644 index eba58109b52..00000000000 --- a/eng/common/templates-official/steps/build-reason.yml +++ /dev/null @@ -1,12 +0,0 @@ -# build-reason.yml -# Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons -# to include steps (',' separated). -parameters: - conditions: '' - steps: [] - -steps: - - ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}: - - ${{ parameters.steps }} - - ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}: - - ${{ parameters.steps }} diff --git a/eng/common/templates-official/steps/component-governance.yml b/eng/common/templates-official/steps/component-governance.yml index cbba0596709..30bb3985ca2 100644 --- a/eng/common/templates-official/steps/component-governance.yml +++ b/eng/common/templates-official/steps/component-governance.yml @@ -1,13 +1,7 @@ -parameters: - disableComponentGovernance: false - componentGovernanceIgnoreDirectories: '' - steps: -- ${{ if eq(parameters.disableComponentGovernance, 'true') }}: - - script: echo "##vso[task.setvariable variable=skipComponentGovernanceDetection]true" - displayName: Set skipComponentGovernanceDetection variable -- ${{ if ne(parameters.disableComponentGovernance, 'true') }}: - - task: ComponentGovernanceComponentDetection@0 - continueOnError: true - inputs: - ignoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} \ No newline at end of file +- template: /eng/common/core-templates/steps/component-governance.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/enable-internal-runtimes.yml b/eng/common/templates-official/steps/enable-internal-runtimes.yml index 93a8394a666..f9dd238c6cd 100644 --- a/eng/common/templates-official/steps/enable-internal-runtimes.yml +++ b/eng/common/templates-official/steps/enable-internal-runtimes.yml @@ -1,28 +1,9 @@ # Obtains internal runtime download credentials and populates the 'dotnetbuilds-internal-container-read-token-base64' # variable with the base64-encoded SAS token, by default - -parameters: -- name: federatedServiceConnection - type: string - default: 'dotnetbuilds-internal-read' -- name: outputVariableName - type: string - default: 'dotnetbuilds-internal-container-read-token-base64' -- name: expiryInHours - type: number - default: 1 -- name: base64Encode - type: boolean - default: true - steps: -- ${{ if ne(variables['System.TeamProject'], 'public') }}: - - template: /eng/common/templates-official/steps/get-delegation-sas.yml - parameters: - federatedServiceConnection: ${{ parameters.federatedServiceConnection }} - outputVariableName: ${{ parameters.outputVariableName }} - expiryInHours: ${{ parameters.expiryInHours }} - base64Encode: ${{ parameters.base64Encode }} - storageAccount: dotnetbuilds - container: internal - permissions: rl +- template: /eng/common/core-templates/steps/enable-internal-runtimes.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/enable-internal-sources.yml b/eng/common/templates-official/steps/enable-internal-sources.yml new file mode 100644 index 00000000000..e6d57182284 --- /dev/null +++ b/eng/common/templates-official/steps/enable-internal-sources.yml @@ -0,0 +1,7 @@ +steps: +- template: /eng/common/core-templates/steps/enable-internal-sources.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/steps/execute-codeql.yml b/eng/common/templates-official/steps/execute-codeql.yml deleted file mode 100644 index 9b4a5ffa30a..00000000000 --- a/eng/common/templates-official/steps/execute-codeql.yml +++ /dev/null @@ -1,32 +0,0 @@ -parameters: - # Language that should be analyzed. Defaults to csharp - language: csharp - # Build Commands - buildCommands: '' - overrideParameters: '' # Optional: to override values for parameters. - additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' - # Optional: if specified, restore and use this version of Guardian instead of the default. - overrideGuardianVersion: '' - # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth - # diagnosis of problems with specific tool configurations. - publishGuardianDirectoryToPipeline: false - # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL - # parameters rather than relying on YAML. It may be better to use a local script, because you can - # reproduce results locally without piecing together a command based on the YAML. - executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' - # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named - # 'continueOnError', the parameter value is not correctly picked up. - # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter - # optional: determines whether to continue the build if the step errors; - sdlContinueOnError: false - -steps: -- template: /eng/common/templates-official/steps/execute-sdl.yml - parameters: - overrideGuardianVersion: ${{ parameters.overrideGuardianVersion }} - executeAllSdlToolsScript: ${{ parameters.executeAllSdlToolsScript }} - overrideParameters: ${{ parameters.overrideParameters }} - additionalParameters: '${{ parameters.additionalParameters }} - -CodeQLAdditionalRunConfigParams @("BuildCommands < ${{ parameters.buildCommands }}", "Language < ${{ parameters.language }}")' - publishGuardianDirectoryToPipeline: ${{ parameters.publishGuardianDirectoryToPipeline }} - sdlContinueOnError: ${{ parameters.sdlContinueOnError }} \ No newline at end of file diff --git a/eng/common/templates-official/steps/execute-sdl.yml b/eng/common/templates-official/steps/execute-sdl.yml deleted file mode 100644 index 301d5c591eb..00000000000 --- a/eng/common/templates-official/steps/execute-sdl.yml +++ /dev/null @@ -1,86 +0,0 @@ -parameters: - overrideGuardianVersion: '' - executeAllSdlToolsScript: '' - overrideParameters: '' - additionalParameters: '' - publishGuardianDirectoryToPipeline: false - sdlContinueOnError: false - condition: '' - -steps: -- task: NuGetAuthenticate@1 - -- task: NuGetToolInstaller@1 - displayName: 'Install NuGet.exe' - -- ${{ if ne(parameters.overrideGuardianVersion, '') }}: - - pwsh: | - Set-Location -Path $(Build.SourcesDirectory)\eng\common\sdl - . .\sdl.ps1 - $guardianCliLocation = Install-Gdn -Path $(Build.SourcesDirectory)\.artifacts -Version ${{ parameters.overrideGuardianVersion }} - Write-Host "##vso[task.setvariable variable=GuardianCliLocation]$guardianCliLocation" - displayName: Install Guardian (Overridden) - -- ${{ if eq(parameters.overrideGuardianVersion, '') }}: - - pwsh: | - Set-Location -Path $(Build.SourcesDirectory)\eng\common\sdl - . .\sdl.ps1 - $guardianCliLocation = Install-Gdn -Path $(Build.SourcesDirectory)\.artifacts - Write-Host "##vso[task.setvariable variable=GuardianCliLocation]$guardianCliLocation" - displayName: Install Guardian - -- ${{ if ne(parameters.overrideParameters, '') }}: - - powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }} - displayName: Execute SDL (Overridden) - continueOnError: ${{ parameters.sdlContinueOnError }} - condition: ${{ parameters.condition }} - -- ${{ if eq(parameters.overrideParameters, '') }}: - - powershell: ${{ parameters.executeAllSdlToolsScript }} - -GuardianCliLocation $(GuardianCliLocation) - -NugetPackageDirectory $(Build.SourcesDirectory)\.packages - -AzureDevOpsAccessToken $(dn-bot-dotnet-build-rw-code-rw) - ${{ parameters.additionalParameters }} - displayName: Execute SDL - continueOnError: ${{ parameters.sdlContinueOnError }} - condition: ${{ parameters.condition }} - -- ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}: - # We want to publish the Guardian results and configuration for easy diagnosis. However, the - # '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default - # tooling files. Some of these files are large and aren't useful during an investigation, so - # exclude them by simply deleting them before publishing. (As of writing, there is no documented - # way to selectively exclude a dir from the pipeline artifact publish task.) - - task: DeleteFiles@1 - displayName: Delete Guardian dependencies to avoid uploading - inputs: - SourceFolder: $(Agent.BuildDirectory)/.gdn - Contents: | - c - i - condition: succeededOrFailed() - - - publish: $(Agent.BuildDirectory)/.gdn - artifact: GuardianConfiguration - displayName: Publish GuardianConfiguration - condition: succeededOrFailed() - - # Publish the SARIF files in a container named CodeAnalysisLogs to enable integration - # with the "SARIF SAST Scans Tab" Azure DevOps extension - - task: CopyFiles@2 - displayName: Copy SARIF files - inputs: - flattenFolders: true - sourceFolder: $(Agent.BuildDirectory)/.gdn/rc/ - contents: '**/*.sarif' - targetFolder: $(Build.SourcesDirectory)/CodeAnalysisLogs - condition: succeededOrFailed() - - # Use PublishBuildArtifacts because the SARIF extension only checks this case - # see microsoft/sarif-azuredevops-extension#4 - - task: PublishBuildArtifacts@1 - displayName: Publish SARIF files to CodeAnalysisLogs container - inputs: - pathToPublish: $(Build.SourcesDirectory)/CodeAnalysisLogs - artifactName: CodeAnalysisLogs - condition: succeededOrFailed() \ No newline at end of file diff --git a/eng/common/templates-official/steps/generate-sbom.yml b/eng/common/templates-official/steps/generate-sbom.yml index 1bf43bf807a..9a89a4706d9 100644 --- a/eng/common/templates-official/steps/generate-sbom.yml +++ b/eng/common/templates-official/steps/generate-sbom.yml @@ -1,48 +1,7 @@ -# BuildDropPath - The root folder of the drop directory for which the manifest file will be generated. -# PackageName - The name of the package this SBOM represents. -# PackageVersion - The version of the package this SBOM represents. -# ManifestDirPath - The path of the directory where the generated manifest files will be placed -# IgnoreDirectories - Directories to ignore for SBOM generation. This will be passed through to the CG component detector. - -parameters: - PackageVersion: 8.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' - PackageName: '.NET' - ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom - IgnoreDirectories: '' - sbomContinueOnError: true - steps: -- task: PowerShell@2 - displayName: Prep for SBOM generation in (Non-linux) - condition: or(eq(variables['Agent.Os'], 'Windows_NT'), eq(variables['Agent.Os'], 'Darwin')) - inputs: - filePath: ./eng/common/generate-sbom-prep.ps1 - arguments: ${{parameters.manifestDirPath}} - -# Chmodding is a workaround for https://github.com/dotnet/arcade/issues/8461 -- script: | - chmod +x ./eng/common/generate-sbom-prep.sh - ./eng/common/generate-sbom-prep.sh ${{parameters.manifestDirPath}} - displayName: Prep for SBOM generation in (Linux) - condition: eq(variables['Agent.Os'], 'Linux') - continueOnError: ${{ parameters.sbomContinueOnError }} - -- task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 - displayName: 'Generate SBOM manifest' - continueOnError: ${{ parameters.sbomContinueOnError }} - inputs: - PackageName: ${{ parameters.packageName }} - BuildDropPath: ${{ parameters.buildDropPath }} - PackageVersion: ${{ parameters.packageVersion }} - ManifestDirPath: ${{ parameters.manifestDirPath }} - ${{ if ne(parameters.IgnoreDirectories, '') }}: - AdditionalComponentDetectorArgs: '--IgnoreDirectories ${{ parameters.IgnoreDirectories }}' - -- task: 1ES.PublishPipelineArtifact@1 - displayName: Publish SBOM manifest - continueOnError: ${{parameters.sbomContinueOnError}} - inputs: - targetPath: '${{parameters.manifestDirPath}}' - artifactName: $(ARTIFACT_NAME) +- template: /eng/common/core-templates/steps/generate-sbom.yml + parameters: + is1ESPipeline: true + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/get-delegation-sas.yml b/eng/common/templates-official/steps/get-delegation-sas.yml index c0e8f91317f..c5a9c1f8275 100644 --- a/eng/common/templates-official/steps/get-delegation-sas.yml +++ b/eng/common/templates-official/steps/get-delegation-sas.yml @@ -1,43 +1,7 @@ -parameters: -- name: federatedServiceConnection - type: string -- name: outputVariableName - type: string -- name: expiryInHours - type: number - default: 1 -- name: base64Encode - type: boolean - default: false -- name: storageAccount - type: string -- name: container - type: string -- name: permissions - type: string - default: 'rl' - steps: -- task: AzureCLI@2 - displayName: 'Generate delegation SAS Token for ${{ parameters.storageAccount }}/${{ parameters.container }}' - inputs: - azureSubscription: ${{ parameters.federatedServiceConnection }} - scriptType: 'pscore' - scriptLocation: 'inlineScript' - inlineScript: | - # Calculate the expiration of the SAS token and convert to UTC - $expiry = (Get-Date).AddHours(${{ parameters.expiryInHours }}).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") - - $sas = az storage container generate-sas --account-name ${{ parameters.storageAccount }} --name ${{ parameters.container }} --permissions ${{ parameters.permissions }} --expiry $expiry --auth-mode login --as-user -o tsv - - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to generate SAS token." - exit 1 - } - - if ('${{ parameters.base64Encode }}' -eq 'true') { - $sas = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sas)) - } +- template: /eng/common/core-templates/steps/get-delegation-sas.yml + parameters: + is1ESPipeline: true - Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true]$sas" + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/get-federated-access-token.yml b/eng/common/templates-official/steps/get-federated-access-token.yml index d556f9c9fb0..c8dcf6b8139 100644 --- a/eng/common/templates-official/steps/get-federated-access-token.yml +++ b/eng/common/templates-official/steps/get-federated-access-token.yml @@ -1,40 +1,7 @@ -parameters: -- name: federatedServiceConnection - type: string -- name: outputVariableName - type: string -- name: stepName - type: string - default: 'getFederatedAccessToken' -- name: condition - type: string - default: '' -# Resource to get a token for. Common values include: -# - '499b84ac-1321-427f-aa17-267ca6975798' for Azure DevOps -# - 'https://storage.azure.com/' for storage -# Defaults to Azure DevOps -- name: resource - type: string - default: '499b84ac-1321-427f-aa17-267ca6975798' -- name: isStepOutputVariable - type: boolean - default: false - steps: -- task: AzureCLI@2 - displayName: 'Getting federated access token for feeds' - name: ${{ parameters.stepName }} - ${{ if ne(parameters.condition, '') }}: - condition: ${{ parameters.condition }} - inputs: - azureSubscription: ${{ parameters.federatedServiceConnection }} - scriptType: 'pscore' - scriptLocation: 'inlineScript' - inlineScript: | - $accessToken = az account get-access-token --query accessToken --resource ${{ parameters.resource }} --output tsv - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to get access token for resource '${{ parameters.resource }}'" - exit 1 - } - Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" +- template: /eng/common/core-templates/steps/get-federated-access-token.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates-official/steps/publish-build-artifacts.yml b/eng/common/templates-official/steps/publish-build-artifacts.yml new file mode 100644 index 00000000000..100a3fc9849 --- /dev/null +++ b/eng/common/templates-official/steps/publish-build-artifacts.yml @@ -0,0 +1,41 @@ +parameters: +- name: displayName + type: string + default: 'Publish to Build Artifact' + +- name: condition + type: string + default: succeeded() + +- name: artifactName + type: string + +- name: pathToPublish + type: string + +- name: continueOnError + type: boolean + default: false + +- name: publishLocation + type: string + default: 'Container' + +- name: is1ESPipeline + type: boolean + default: true + +steps: +- ${{ if ne(parameters.is1ESPipeline, true) }}: + - 'eng/common/templates-official cannot be referenced from a non-1ES managed template': error +- task: 1ES.PublishBuildArtifacts@1 + displayName: ${{ parameters.displayName }} + condition: ${{ parameters.condition }} + ${{ if parameters.continueOnError }}: + continueOnError: ${{ parameters.continueOnError }} + inputs: + PublishLocation: ${{ parameters.publishLocation }} + PathtoPublish: ${{ parameters.pathToPublish }} + ${{ if parameters.artifactName }}: + ArtifactName: ${{ parameters.artifactName }} + diff --git a/eng/common/templates-official/steps/publish-logs.yml b/eng/common/templates-official/steps/publish-logs.yml index 04012fed182..579fd531e94 100644 --- a/eng/common/templates-official/steps/publish-logs.yml +++ b/eng/common/templates-official/steps/publish-logs.yml @@ -1,23 +1,7 @@ -parameters: - StageLabel: '' - JobLabel: '' - steps: -- task: Powershell@2 - displayName: Prepare Binlogs to Upload - inputs: - targetType: inline - script: | - New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ - Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ - continueOnError: true - condition: always() +- template: /eng/common/core-templates/steps/publish-logs.yml + parameters: + is1ESPipeline: true -- task: 1ES.PublishBuildArtifacts@1 - displayName: Publish Logs - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' - PublishLocation: Container - ArtifactName: PostBuildLogs - continueOnError: true - condition: always() + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/publish-pipeline-artifacts.yml b/eng/common/templates-official/steps/publish-pipeline-artifacts.yml new file mode 100644 index 00000000000..172f9f0fdc9 --- /dev/null +++ b/eng/common/templates-official/steps/publish-pipeline-artifacts.yml @@ -0,0 +1,28 @@ +parameters: +- name: is1ESPipeline + type: boolean + default: true + +- name: args + type: object + default: {} + +steps: +- ${{ if ne(parameters.is1ESPipeline, true) }}: + - 'eng/common/templates-official cannot be referenced from a non-1ES managed template': error +- task: 1ES.PublishPipelineArtifact@1 + displayName: ${{ coalesce(parameters.args.displayName, 'Publish to Build Artifact') }} + ${{ if parameters.args.condition }}: + condition: ${{ parameters.args.condition }} + ${{ else }}: + condition: succeeded() + ${{ if parameters.args.continueOnError }}: + continueOnError: ${{ parameters.args.continueOnError }} + inputs: + targetPath: ${{ parameters.args.targetPath }} + ${{ if parameters.args.artifactName }}: + artifactName: ${{ parameters.args.artifactName }} + ${{ if parameters.args.properties }}: + properties: ${{ parameters.args.properties }} + ${{ if parameters.args.sbomEnabled }}: + sbomEnabled: ${{ parameters.args.sbomEnabled }} diff --git a/eng/common/templates-official/steps/retain-build.yml b/eng/common/templates-official/steps/retain-build.yml index 83d97a26a01..5594551508a 100644 --- a/eng/common/templates-official/steps/retain-build.yml +++ b/eng/common/templates-official/steps/retain-build.yml @@ -1,28 +1,7 @@ -parameters: - # Optional azure devops PAT with build execute permissions for the build's organization, - # only needed if the build that should be retained ran on a different organization than - # the pipeline where this template is executing from - Token: '' - # Optional BuildId to retain, defaults to the current running build - BuildId: '' - # Azure devops Organization URI for the build in the https://dev.azure.com/ format. - # Defaults to the organization the current pipeline is running on - AzdoOrgUri: '$(System.CollectionUri)' - # Azure devops project for the build. Defaults to the project the current pipeline is running on - AzdoProject: '$(System.TeamProject)' - steps: - - task: powershell@2 - inputs: - targetType: 'filePath' - filePath: eng/common/retain-build.ps1 - pwsh: true - arguments: > - -AzdoOrgUri: ${{parameters.AzdoOrgUri}} - -AzdoProject ${{parameters.AzdoProject}} - -Token ${{coalesce(parameters.Token, '$env:SYSTEM_ACCESSTOKEN') }} - -BuildId ${{coalesce(parameters.BuildId, '$env:BUILD_ID')}} - displayName: Enable permanent build retention - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - BUILD_ID: $(Build.BuildId) \ No newline at end of file +- template: /eng/common/core-templates/steps/retain-build.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/send-to-helix.yml b/eng/common/templates-official/steps/send-to-helix.yml index 3eb7e2d5f84..6500f21bf84 100644 --- a/eng/common/templates-official/steps/send-to-helix.yml +++ b/eng/common/templates-official/steps/send-to-helix.yml @@ -1,91 +1,7 @@ -# Please remember to update the documentation if you make changes to these parameters! -parameters: - HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ - HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' - HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number - HelixTargetQueues: '' # required -- semicolon-delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues - HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group - HelixConfiguration: '' # optional -- additional property attached to a job - HelixPreCommands: '' # optional -- commands to run before Helix work item execution - HelixPostCommands: '' # optional -- commands to run after Helix work item execution - WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects - WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects - WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects - CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload - XUnitProjects: '' # optional -- semicolon-delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true - XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects - XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects - XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner - XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects - IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion - DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json - DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json - WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." - IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set - HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting https://helix.int-dot.net ) - Creator: '' # optional -- if the build is external, use this to specify who is sending the job - DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO - condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() - continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false - steps: - - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' - displayName: ${{ parameters.DisplayNamePrefix }} (Windows) - env: - BuildConfig: $(_BuildConfig) - HelixSource: ${{ parameters.HelixSource }} - HelixType: ${{ parameters.HelixType }} - HelixBuild: ${{ parameters.HelixBuild }} - HelixConfiguration: ${{ parameters.HelixConfiguration }} - HelixTargetQueues: ${{ parameters.HelixTargetQueues }} - HelixAccessToken: ${{ parameters.HelixAccessToken }} - HelixPreCommands: ${{ parameters.HelixPreCommands }} - HelixPostCommands: ${{ parameters.HelixPostCommands }} - WorkItemDirectory: ${{ parameters.WorkItemDirectory }} - WorkItemCommand: ${{ parameters.WorkItemCommand }} - WorkItemTimeout: ${{ parameters.WorkItemTimeout }} - CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} - XUnitProjects: ${{ parameters.XUnitProjects }} - XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} - XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} - XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} - XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} - IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} - DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} - DotNetCliVersion: ${{ parameters.DotNetCliVersion }} - WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} - HelixBaseUri: ${{ parameters.HelixBaseUri }} - Creator: ${{ parameters.Creator }} - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} - - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog - displayName: ${{ parameters.DisplayNamePrefix }} (Unix) - env: - BuildConfig: $(_BuildConfig) - HelixSource: ${{ parameters.HelixSource }} - HelixType: ${{ parameters.HelixType }} - HelixBuild: ${{ parameters.HelixBuild }} - HelixConfiguration: ${{ parameters.HelixConfiguration }} - HelixTargetQueues: ${{ parameters.HelixTargetQueues }} - HelixAccessToken: ${{ parameters.HelixAccessToken }} - HelixPreCommands: ${{ parameters.HelixPreCommands }} - HelixPostCommands: ${{ parameters.HelixPostCommands }} - WorkItemDirectory: ${{ parameters.WorkItemDirectory }} - WorkItemCommand: ${{ parameters.WorkItemCommand }} - WorkItemTimeout: ${{ parameters.WorkItemTimeout }} - CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} - XUnitProjects: ${{ parameters.XUnitProjects }} - XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} - XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} - XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} - XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} - IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} - DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} - DotNetCliVersion: ${{ parameters.DotNetCliVersion }} - WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} - HelixBaseUri: ${{ parameters.HelixBaseUri }} - Creator: ${{ parameters.Creator }} - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} +- template: /eng/common/core-templates/steps/send-to-helix.yml + parameters: + is1ESPipeline: true + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates-official/steps/source-build.yml b/eng/common/templates-official/steps/source-build.yml index 829f17c34d1..8f92c49e7b0 100644 --- a/eng/common/templates-official/steps/source-build.yml +++ b/eng/common/templates-official/steps/source-build.yml @@ -1,129 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. - - # This is a 'steps' template, and is intended for advanced scenarios where the existing build - # infra has a careful build methodology that must be followed. For example, a repo - # (dotnet/runtime) might choose to clone the GitHub repo only once and store it as a pipeline - # artifact for all subsequent jobs to use, to reduce dependence on a strong network connection to - # GitHub. Using this steps template leaves room for that infra to be included. - - # Defines the platform on which to run the steps. See 'eng/common/templates-official/job/source-build.yml' - # for details. The entire object is described in the 'job' template for simplicity, even though - # the usage of the properties on this object is split between the 'job' and 'steps' templates. - platform: {} - steps: -# Build. Keep it self-contained for simple reusability. (No source-build-specific job variables.) -- script: | - set -x - df -h - - # If building on the internal project, the artifact feeds variable may be available (usually only if needed) - # In that case, call the feed setup script to add internal feeds corresponding to public ones. - # In addition, add an msbuild argument to copy the WIP from the repo to the target build location. - # This is because SetupNuGetSources.sh will alter the current NuGet.config file, and we need to preserve those - # changes. - internalRestoreArgs= - if [ '$(dn-bot-dnceng-artifact-feeds-rw)' != '$''(dn-bot-dnceng-artifact-feeds-rw)' ]; then - # Temporarily work around https://github.com/dotnet/arcade/issues/7709 - chmod +x $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh - $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh $(Build.SourcesDirectory)/NuGet.config $(dn-bot-dnceng-artifact-feeds-rw) - internalRestoreArgs='/p:CopyWipIntoInnerSourceBuildRepo=true' - - # The 'Copy WIP' feature of source build uses git stash to apply changes from the original repo. - # This only works if there is a username/email configured, which won't be the case in most CI runs. - git config --get user.email - if [ $? -ne 0 ]; then - git config user.email dn-bot@microsoft.com - git config user.name dn-bot - fi - fi - - # If building on the internal project, the internal storage variable may be available (usually only if needed) - # In that case, add variables to allow the download of internal runtimes if the specified versions are not found - # in the default public locations. - internalRuntimeDownloadArgs= - if [ '$(dotnetbuilds-internal-container-read-token-base64)' != '$''(dotnetbuilds-internal-container-read-token-base64)' ]; then - internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://dotnetbuilds.blob.core.windows.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://dotnetbuilds.blob.core.windows.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' - fi - - buildConfig=Release - # Check if AzDO substitutes in a build config from a variable, and use it if so. - if [ '$(_BuildConfig)' != '$''(_BuildConfig)' ]; then - buildConfig='$(_BuildConfig)' - fi - - officialBuildArgs= - if [ '${{ and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}' = 'True' ]; then - officialBuildArgs='/p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER)' - fi - - targetRidArgs= - if [ '${{ parameters.platform.targetRID }}' != '' ]; then - targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' - fi - - runtimeOsArgs= - if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then - runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}' - fi - - baseOsArgs= - if [ '${{ parameters.platform.baseOS }}' != '' ]; then - baseOsArgs='/p:BaseOS=${{ parameters.platform.baseOS }}' - fi - - publishArgs= - if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then - publishArgs='--publish' - fi - - assetManifestFileName=SourceBuild_RidSpecific.xml - if [ '${{ parameters.platform.name }}' != '' ]; then - assetManifestFileName=SourceBuild_${{ parameters.platform.name }}.xml - fi - - ${{ coalesce(parameters.platform.buildScript, './build.sh') }} --ci \ - --configuration $buildConfig \ - --restore --build --pack $publishArgs -bl \ - $officialBuildArgs \ - $internalRuntimeDownloadArgs \ - $internalRestoreArgs \ - $targetRidArgs \ - $runtimeOsArgs \ - $baseOsArgs \ - /p:SourceBuildNonPortable=${{ parameters.platform.nonPortable }} \ - /p:ArcadeBuildFromSource=true \ - /p:AssetManifestFileName=$assetManifestFileName - displayName: Build - -# Upload build logs for diagnosis. -- task: CopyFiles@2 - displayName: Prepare BuildLogs staging directory - inputs: - SourceFolder: '$(Build.SourcesDirectory)' - Contents: | - **/*.log - **/*.binlog - artifacts/source-build/self/prebuilt-report/** - TargetFolder: '$(Build.StagingDirectory)/BuildLogs' - CleanTargetFolder: true - continueOnError: true - condition: succeededOrFailed() - -- task: 1ES.PublishPipelineArtifact@1 - displayName: Publish BuildLogs - inputs: - targetPath: '$(Build.StagingDirectory)/BuildLogs' - artifactName: BuildLogs_SourceBuild_${{ parameters.platform.name }}_Attempt$(System.JobAttempt) - continueOnError: true - condition: succeededOrFailed() +- template: /eng/common/core-templates/steps/source-build.yml + parameters: + is1ESPipeline: true -# Manually inject component detection so that we can ignore the source build upstream cache, which contains -# a nupkg cache of input packages (a local feed). -# This path must match the upstream cache path in property 'CurrentRepoSourceBuiltNupkgCacheDir' -# in src\Microsoft.DotNet.Arcade.Sdk\tools\SourceBuild\SourceBuildArcade.targets -- task: ComponentGovernanceComponentDetection@0 - displayName: Component Detection (Exclude upstream cache) - inputs: - ignoreDirectories: '$(Build.SourcesDirectory)/artifacts/source-build/self/src/artifacts/obj/source-built-upstream-cache' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/job/execute-sdl.yml b/eng/common/templates/job/execute-sdl.yml deleted file mode 100644 index 7870f93bc17..00000000000 --- a/eng/common/templates/job/execute-sdl.yml +++ /dev/null @@ -1,139 +0,0 @@ -parameters: - enable: 'false' # Whether the SDL validation job should execute or not - overrideParameters: '' # Optional: to override values for parameters. - additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' - # Optional: if specified, restore and use this version of Guardian instead of the default. - overrideGuardianVersion: '' - # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth - # diagnosis of problems with specific tool configurations. - publishGuardianDirectoryToPipeline: false - # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL - # parameters rather than relying on YAML. It may be better to use a local script, because you can - # reproduce results locally without piecing together a command based on the YAML. - executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' - # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named - # 'continueOnError', the parameter value is not correctly picked up. - # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter - sdlContinueOnError: false # optional: determines whether to continue the build if the step errors; - # optional: determines if build artifacts should be downloaded. - downloadArtifacts: true - # optional: determines if this job should search the directory of downloaded artifacts for - # 'tar.gz' and 'zip' archive files and extract them before running SDL validation tasks. - extractArchiveArtifacts: false - dependsOn: '' # Optional: dependencies of the job - artifactNames: '' # Optional: patterns supplied to DownloadBuildArtifacts - # Usage: - # artifactNames: - # - 'BlobArtifacts' - # - 'Artifacts_Windows_NT_Release' - # Optional: download a list of pipeline artifacts. 'downloadArtifacts' controls build artifacts, - # not pipeline artifacts, so doesn't affect the use of this parameter. - pipelineArtifactNames: [] - -jobs: -- job: Run_SDL - dependsOn: ${{ parameters.dependsOn }} - displayName: Run SDL tool - condition: and(succeededOrFailed(), eq( ${{ parameters.enable }}, 'true')) - variables: - - group: DotNet-VSTS-Bot - - name: AzDOProjectName - value: ${{ parameters.AzDOProjectName }} - - name: AzDOPipelineId - value: ${{ parameters.AzDOPipelineId }} - - name: AzDOBuildId - value: ${{ parameters.AzDOBuildId }} - - template: /eng/common/templates/variables/sdl-variables.yml - - name: GuardianVersion - value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} - - template: /eng/common/templates/variables/pool-providers.yml - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - steps: - - checkout: self - clean: true - - # If the template caller didn't provide an AzDO parameter, set them all up as Maestro vars. - - ${{ if not(and(parameters.AzDOProjectName, parameters.AzDOPipelineId, parameters.AzDOBuildId)) }}: - - template: /eng/common/templates/post-build/setup-maestro-vars.yml - - - ${{ if ne(parameters.downloadArtifacts, 'false')}}: - - ${{ if ne(parameters.artifactNames, '') }}: - - ${{ each artifactName in parameters.artifactNames }}: - - task: DownloadBuildArtifacts@0 - displayName: Download Build Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: ${{ artifactName }} - downloadPath: $(Build.ArtifactStagingDirectory)\artifacts - checkDownloadedFiles: true - - ${{ if eq(parameters.artifactNames, '') }}: - - task: DownloadBuildArtifacts@0 - displayName: Download Build Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - downloadType: specific files - itemPattern: "**" - downloadPath: $(Build.ArtifactStagingDirectory)\artifacts - checkDownloadedFiles: true - - - ${{ each artifactName in parameters.pipelineArtifactNames }}: - - task: DownloadPipelineArtifact@2 - displayName: Download Pipeline Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: ${{ artifactName }} - downloadPath: $(Build.ArtifactStagingDirectory)\artifacts - checkDownloadedFiles: true - - - powershell: eng/common/sdl/trim-assets-version.ps1 - -InputPath $(Build.ArtifactStagingDirectory)\artifacts - displayName: Trim the version from the NuGet packages - continueOnError: ${{ parameters.sdlContinueOnError }} - - - powershell: eng/common/sdl/extract-artifact-packages.ps1 - -InputPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts - -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\BlobArtifacts - displayName: Extract Blob Artifacts - continueOnError: ${{ parameters.sdlContinueOnError }} - - - powershell: eng/common/sdl/extract-artifact-packages.ps1 - -InputPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts - -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts\PackageArtifacts - displayName: Extract Package Artifacts - continueOnError: ${{ parameters.sdlContinueOnError }} - - - ${{ if ne(parameters.extractArchiveArtifacts, 'false') }}: - - powershell: eng/common/sdl/extract-artifact-archives.ps1 - -InputPath $(Build.ArtifactStagingDirectory)\artifacts - -ExtractPath $(Build.ArtifactStagingDirectory)\artifacts - displayName: Extract Archive Artifacts - continueOnError: ${{ parameters.sdlContinueOnError }} - - - template: /eng/common/templates/steps/execute-sdl.yml - parameters: - overrideGuardianVersion: ${{ parameters.overrideGuardianVersion }} - executeAllSdlToolsScript: ${{ parameters.executeAllSdlToolsScript }} - overrideParameters: ${{ parameters.overrideParameters }} - additionalParameters: ${{ parameters.additionalParameters }} - publishGuardianDirectoryToPipeline: ${{ parameters.publishGuardianDirectoryToPipeline }} - sdlContinueOnError: ${{ parameters.sdlContinueOnError }} diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 8ec5c4f2d9f..8da477dd69f 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -1,259 +1,89 @@ -# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, -# and some (Microbuild) should only be applied to non-PR cases for internal builds. - -parameters: -# Job schema parameters - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - cancelTimeoutInMinutes: '' - condition: '' - container: '' - continueOnError: false - dependsOn: '' - displayName: '' - pool: '' - steps: [] - strategy: '' - timeoutInMinutes: '' - variables: [] - workspace: '' - templateContext: '' - -# Job base template specific parameters - # See schema documentation - https://github.com/dotnet/arcade/blob/master/Documentation/AzureDevOps/TemplateSchema.md - artifacts: '' - enableMicrobuild: false +parameters: enablePublishBuildArtifacts: false - enablePublishBuildAssets: false - enablePublishTestResults: false - enablePublishUsingPipelines: false - enableBuildRetry: false disableComponentGovernance: '' componentGovernanceIgnoreDirectories: '' - mergeTestResults: false - testRunTitle: '' - testResultsFormat: '' - name: '' - preSteps: [] - runAsPublic: false # Sbom related params enableSbom: true - PackageVersion: 7.0.0 + PackageVersion: 9.0.0 BuildDropPath: '$(Build.SourcesDirectory)/artifacts' jobs: -- job: ${{ parameters.name }} - - ${{ if ne(parameters.cancelTimeoutInMinutes, '') }}: - cancelTimeoutInMinutes: ${{ parameters.cancelTimeoutInMinutes }} - - ${{ if ne(parameters.condition, '') }}: - condition: ${{ parameters.condition }} - - ${{ if ne(parameters.container, '') }}: - container: ${{ parameters.container }} - - ${{ if ne(parameters.continueOnError, '') }}: - continueOnError: ${{ parameters.continueOnError }} - - ${{ if ne(parameters.dependsOn, '') }}: - dependsOn: ${{ parameters.dependsOn }} - - ${{ if ne(parameters.displayName, '') }}: - displayName: ${{ parameters.displayName }} - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - - ${{ if ne(parameters.strategy, '') }}: - strategy: ${{ parameters.strategy }} - - ${{ if ne(parameters.timeoutInMinutes, '') }}: - timeoutInMinutes: ${{ parameters.timeoutInMinutes }} - - ${{ if ne(parameters.templateContext, '') }}: - templateContext: ${{ parameters.templateContext }} - - variables: - - ${{ if ne(parameters.enableTelemetry, 'false') }}: - - name: DOTNET_CLI_TELEMETRY_PROFILE - value: '$(Build.Repository.Uri)' - - ${{ if eq(parameters.enableRichCodeNavigation, 'true') }}: - - name: EnableRichCodeNavigation - value: 'true' - # Retry signature validation up to three times, waiting 2 seconds between attempts. - # See https://learn.microsoft.com/en-us/nuget/reference/errors-and-warnings/nu3028#retry-untrusted-root-failures - - name: NUGET_EXPERIMENTAL_CHAIN_BUILD_RETRY_POLICY - value: 3,2000 - - ${{ each variable in parameters.variables }}: - # handle name-value variable syntax - # example: - # - name: [key] - # value: [value] - - ${{ if ne(variable.name, '') }}: - - name: ${{ variable.name }} - value: ${{ variable.value }} - - # handle variable groups - - ${{ if ne(variable.group, '') }}: - - group: ${{ variable.group }} - - # handle template variable syntax - # example: - # - template: path/to/template.yml - # parameters: - # [key]: [value] - - ${{ if ne(variable.template, '') }}: - - template: ${{ variable.template }} - ${{ if ne(variable.parameters, '') }}: - parameters: ${{ variable.parameters }} - - # handle key-value variable syntax. - # example: - # - [key]: [value] - - ${{ if and(eq(variable.name, ''), eq(variable.group, ''), eq(variable.template, '')) }}: - - ${{ each pair in variable }}: - - name: ${{ pair.key }} - value: ${{ pair.value }} - - # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds - - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - group: DotNet-HelixApi-Access - - ${{ if ne(parameters.workspace, '') }}: - workspace: ${{ parameters.workspace }} - - steps: - - ${{ if ne(parameters.preSteps, '') }}: - - ${{ each preStep in parameters.preSteps }}: - - ${{ preStep }} - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - task: MicroBuildSigningPlugin@3 - displayName: Install MicroBuild plugin - inputs: - signType: $(_SignType) - zipSources: false - feedSource: https://dnceng.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json - env: - TeamName: $(_TeamName) - continueOnError: ${{ parameters.continueOnError }} - condition: and(succeeded(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - - - ${{ if and(eq(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'internal')) }}: - - task: NuGetAuthenticate@1 - - - ${{ if and(ne(parameters.artifacts.download, 'false'), ne(parameters.artifacts.download, '')) }}: - - task: DownloadPipelineArtifact@2 - inputs: - buildType: current - artifactName: ${{ coalesce(parameters.artifacts.download.name, 'Artifacts_$(Agent.OS)_$(_BuildConfig)') }} - targetPath: ${{ coalesce(parameters.artifacts.download.path, 'artifacts') }} - itemPattern: ${{ coalesce(parameters.artifacts.download.pattern, '**') }} - - - ${{ each step in parameters.steps }}: - - ${{ step }} - - - ${{ if eq(parameters.enableRichCodeNavigation, true) }}: - - task: RichCodeNavIndexer@0 - displayName: RichCodeNav Upload - inputs: - languages: ${{ coalesce(parameters.richCodeNavigationLanguage, 'csharp') }} - environment: ${{ coalesce(parameters.richCodeNavigationEnvironment, 'production') }} - richNavLogOutputDirectory: $(Build.SourcesDirectory)/artifacts/bin - uploadRichNavArtifacts: ${{ coalesce(parameters.richCodeNavigationUploadArtifacts, false) }} - continueOnError: true - - - template: /eng/common/templates/steps/component-governance.yml - parameters: - ${{ if eq(parameters.disableComponentGovernance, '') }}: - ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/dotnet/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/microsoft/'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))) }}: - disableComponentGovernance: false - ${{ else }}: - disableComponentGovernance: true - ${{ else }}: - disableComponentGovernance: ${{ parameters.disableComponentGovernance }} - componentGovernanceIgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} - - - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: MicroBuildCleanup@1 - displayName: Execute Microbuild cleanup tasks - condition: and(always(), in(variables['_SignType'], 'real', 'test'), eq(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} - env: - TeamName: $(_TeamName) - - - ${{ if ne(parameters.artifacts.publish, '') }}: - - ${{ if and(ne(parameters.artifacts.publish.artifacts, 'false'), ne(parameters.artifacts.publish.artifacts, '')) }}: - - task: CopyFiles@2 - displayName: Gather binaries for publish to artifacts - inputs: - SourceFolder: 'artifacts/bin' - Contents: '**' - TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/bin' - - task: CopyFiles@2 - displayName: Gather packages for publish to artifacts - inputs: - SourceFolder: 'artifacts/packages' - Contents: '**' - TargetFolder: '$(Build.ArtifactStagingDirectory)/artifacts/packages' - - task: PublishBuildArtifacts@1 - displayName: Publish pipeline artifacts - inputs: - PathtoPublish: '$(Build.ArtifactStagingDirectory)/artifacts' - PublishLocation: Container - ArtifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} - continueOnError: true - condition: always() - - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: - - publish: artifacts/log - artifact: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} - displayName: Publish logs - continueOnError: true - condition: always() - - - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: - - task: PublishBuildArtifacts@1 - displayName: Publish Logs - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' - PublishLocation: Container - ArtifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} - continueOnError: true - condition: always() - - - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'xunit')) }}: - - task: PublishTestResults@2 - displayName: Publish XUnit Test Results - inputs: - testResultsFormat: 'xUnit' - testResultsFiles: '*.xml' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-xunit - mergeTestResults: ${{ parameters.mergeTestResults }} - continueOnError: true - condition: always() - - ${{ if or(and(eq(parameters.enablePublishTestResults, 'true'), eq(parameters.testResultsFormat, '')), eq(parameters.testResultsFormat, 'vstest')) }}: - - task: PublishTestResults@2 - displayName: Publish TRX Test Results - inputs: - testResultsFormat: 'VSTest' - testResultsFiles: '*.trx' - searchFolder: '$(Build.SourcesDirectory)/artifacts/TestResults/$(_BuildConfig)' - testRunTitle: ${{ coalesce(parameters.testRunTitle, parameters.name, '$(System.JobName)') }}-trx - mergeTestResults: ${{ parameters.mergeTestResults }} - continueOnError: true - condition: always() - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: - - template: /eng/common/templates/steps/generate-sbom.yml - parameters: - PackageVersion: ${{ parameters.packageVersion}} - BuildDropPath: ${{ parameters.buildDropPath }} - IgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} - - - ${{ if eq(parameters.enableBuildRetry, 'true') }}: - - publish: $(Build.SourcesDirectory)\eng\common\BuildConfiguration - artifact: BuildConfiguration - displayName: Publish build retry configuration - continueOnError: true +- template: /eng/common/core-templates/job/job.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ if and(ne(parameter.key, 'steps'), ne(parameter.key, 'is1ESPipeline')) }}: + ${{ parameter.key }}: ${{ parameter.value }} + + steps: + - ${{ each step in parameters.steps }}: + - ${{ step }} + + componentGovernanceSteps: + - template: /eng/common/templates/steps/component-governance.yml + parameters: + ${{ if eq(parameters.disableComponentGovernance, '') }}: + ${{ if and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.runAsPublic, 'false'), or(startsWith(variables['Build.SourceBranch'], 'refs/heads/release/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/dotnet/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/microsoft/'), eq(variables['Build.SourceBranch'], 'refs/heads/main'))) }}: + disableComponentGovernance: false + ${{ else }}: + disableComponentGovernance: true + ${{ else }}: + disableComponentGovernance: ${{ parameters.disableComponentGovernance }} + componentGovernanceIgnoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} + + - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest'), eq(parameters.enableSbom, 'true')) }}: + - template: /eng/common/templates/steps/generate-sbom.yml + parameters: + PackageVersion: ${{ parameters.packageVersion }} + BuildDropPath: ${{ parameters.buildDropPath }} + publishArtifacts: false + + + artifactPublishSteps: + - ${{ if ne(parameters.artifacts.publish, '') }}: + - ${{ if and(ne(parameters.artifacts.publish.artifacts, 'false'), ne(parameters.artifacts.publish.artifacts, '')) }}: + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: false + args: + displayName: Publish pipeline artifacts + pathToPublish: '$(Build.ArtifactStagingDirectory)/artifacts' + publishLocation: Container + artifactName: ${{ coalesce(parameters.artifacts.publish.artifacts.name , 'Artifacts_$(Agent.Os)_$(_BuildConfig)') }} + continueOnError: true + condition: always() + - ${{ if and(ne(parameters.artifacts.publish.logs, 'false'), ne(parameters.artifacts.publish.logs, '')) }}: + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: false + args: + targetPath: '$(Build.ArtifactStagingDirectory)/artifacts/log' + artifactName: ${{ coalesce(parameters.artifacts.publish.logs.name, 'Logs_Build_$(Agent.Os)_$(_BuildConfig)') }} + displayName: 'Publish logs' + continueOnError: true + condition: always() + sbomEnabled: false # we don't need SBOM for logs + + - ${{ if ne(parameters.enablePublishBuildArtifacts, 'false') }}: + - template: /eng/common/core-templates/steps/publish-build-artifacts.yml + parameters: + is1ESPipeline: false + args: + displayName: Publish Logs + pathToPublish: '$(Build.ArtifactStagingDirectory)/artifacts/log/$(_BuildConfig)' + publishLocation: Container + artifactName: ${{ coalesce(parameters.enablePublishBuildArtifacts.artifactName, '$(Agent.Os)_$(Agent.JobName)' ) }} + continueOnError: true + condition: always() + + - ${{ if eq(parameters.enableBuildRetry, 'true') }}: + - template: /eng/common/core-templates/steps/publish-pipeline-artifacts.yml + parameters: + is1ESPipeline: false + args: + targetPath: '$(Build.SourcesDirectory)\eng\common\BuildConfiguration' + artifactName: 'BuildConfiguration' + displayName: 'Publish build retry configuration' + continueOnError: true + sbomEnabled: false # we don't need SBOM for BuildConfiguration diff --git a/eng/common/templates/job/onelocbuild.yml b/eng/common/templates/job/onelocbuild.yml index 60ab00c4de3..ff829dc4c70 100644 --- a/eng/common/templates/job/onelocbuild.yml +++ b/eng/common/templates/job/onelocbuild.yml @@ -1,109 +1,7 @@ -parameters: - # Optional: dependencies of the job - dependsOn: '' - - # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool - pool: '' - - CeapexPat: $(dn-bot-ceapex-package-r) # PAT for the loc AzDO instance https://dev.azure.com/ceapex - GithubPat: $(BotAccount-dotnet-bot-repo-PAT) - - SourcesDirectory: $(Build.SourcesDirectory) - CreatePr: true - AutoCompletePr: false - ReusePr: true - UseLfLineEndings: true - UseCheckedInLocProjectJson: false - SkipLocProjectJsonGeneration: false - LanguageSet: VS_Main_Languages - LclSource: lclFilesInRepo - LclPackageId: '' - RepoType: gitHub - GitHubOrg: dotnet - MirrorRepo: '' - MirrorBranch: main - condition: '' - JobNameSuffix: '' - jobs: -- job: OneLocBuild${{ parameters.JobNameSuffix }} - - dependsOn: ${{ parameters.dependsOn }} - - displayName: OneLocBuild${{ parameters.JobNameSuffix }} - - variables: - - group: OneLocBuildVariables # Contains the CeapexPat and GithubPat - - name: _GenerateLocProjectArguments - value: -SourcesDirectory ${{ parameters.SourcesDirectory }} - -LanguageSet "${{ parameters.LanguageSet }}" - -CreateNeutralXlfs - - ${{ if eq(parameters.UseCheckedInLocProjectJson, 'true') }}: - - name: _GenerateLocProjectArguments - value: ${{ variables._GenerateLocProjectArguments }} -UseCheckedInLocProjectJson - - template: /eng/common/templates/variables/pool-providers.yml - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - ${{ if eq(parameters.pool, '') }}: - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - - steps: - - ${{ if ne(parameters.SkipLocProjectJsonGeneration, 'true') }}: - - task: Powershell@2 - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/generate-locproject.ps1 - arguments: $(_GenerateLocProjectArguments) - displayName: Generate LocProject.json - condition: ${{ parameters.condition }} - - - task: OneLocBuild@2 - displayName: OneLocBuild - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - locProj: eng/Localize/LocProject.json - outDir: $(Build.ArtifactStagingDirectory) - lclSource: ${{ parameters.LclSource }} - lclPackageId: ${{ parameters.LclPackageId }} - isCreatePrSelected: ${{ parameters.CreatePr }} - isAutoCompletePrSelected: ${{ parameters.AutoCompletePr }} - ${{ if eq(parameters.CreatePr, true) }}: - isUseLfLineEndingsSelected: ${{ parameters.UseLfLineEndings }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - isShouldReusePrSelected: ${{ parameters.ReusePr }} - packageSourceAuth: patAuth - patVariable: ${{ parameters.CeapexPat }} - ${{ if eq(parameters.RepoType, 'gitHub') }}: - repoType: ${{ parameters.RepoType }} - gitHubPatVariable: "${{ parameters.GithubPat }}" - ${{ if ne(parameters.MirrorRepo, '') }}: - isMirrorRepoSelected: true - gitHubOrganization: ${{ parameters.GitHubOrg }} - mirrorRepo: ${{ parameters.MirrorRepo }} - mirrorBranch: ${{ parameters.MirrorBranch }} - condition: ${{ parameters.condition }} - - - task: PublishBuildArtifacts@1 - displayName: Publish Localization Files - inputs: - PathtoPublish: '$(Build.ArtifactStagingDirectory)/loc' - PublishLocation: Container - ArtifactName: Loc - condition: ${{ parameters.condition }} +- template: /eng/common/core-templates/job/onelocbuild.yml + parameters: + is1ESPipeline: false - - task: PublishBuildArtifacts@1 - displayName: Publish LocProject.json - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/eng/Localize/' - PublishLocation: Container - ArtifactName: Loc - condition: ${{ parameters.condition }} \ No newline at end of file + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/job/publish-build-assets.yml b/eng/common/templates/job/publish-build-assets.yml index cc2b346ba8b..ab2edec2adb 100644 --- a/eng/common/templates/job/publish-build-assets.yml +++ b/eng/common/templates/job/publish-build-assets.yml @@ -1,156 +1,7 @@ -parameters: - configuration: 'Debug' - - # Optional: condition for the job to run - condition: '' - - # Optional: 'true' if future jobs should run even if this job fails - continueOnError: false - - # Optional: dependencies of the job - dependsOn: '' - - # Optional: Include PublishBuildArtifacts task - enablePublishBuildArtifacts: false - - # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool - pool: {} - - # Optional: should run as a public build even in the internal project - # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. - runAsPublic: false - - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing - publishUsingPipelines: false - - # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing - publishAssetsImmediately: false - - artifactsPublishingAdditionalParameters: '' - - signingValidationAdditionalParameters: '' - jobs: -- job: Asset_Registry_Publish - - dependsOn: ${{ parameters.dependsOn }} - timeoutInMinutes: 150 - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - displayName: Publish Assets - ${{ else }}: - displayName: Publish to Build Asset Registry - - variables: - - template: /eng/common/templates/variables/pool-providers.yml - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - group: Publish-Build-Assets - - group: AzureDevOps-Artifact-Feeds-Pats - - name: runCodesignValidationInjection - value: false - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - - template: /eng/common/templates/post-build/common-variables.yml - - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ if ne(variables['System.TeamProject'], 'DevDiv') }}: - name: NetCore1ESPool-Publishing-Internal - demands: ImageOverride -equals windows.vs2019.amd64 - - steps: - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: DownloadBuildArtifacts@0 - displayName: Download artifact - inputs: - artifactName: AssetManifests - downloadPath: '$(Build.StagingDirectory)/Download' - checkDownloadedFiles: true - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} - - - task: NuGetAuthenticate@1 - - - task: AzureCLI@2 - displayName: Publish Build Assets - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/sdk-task.ps1 - arguments: > - -task PublishBuildAssets -restore -msbuildEngine dotnet - /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' - /p:MaestroApiEndpoint=https://maestro.dot.net - /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} - /p:OfficialBuildId=$(Build.BuildNumber) - condition: ${{ parameters.condition }} - continueOnError: ${{ parameters.continueOnError }} - - - task: powershell@2 - displayName: Create ReleaseConfigs Artifact - inputs: - targetType: inline - script: | - Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(BARBuildId) - Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value "$(DefaultChannels)" - Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(IsStableBuild) - - - task: PublishBuildArtifacts@1 - displayName: Publish ReleaseConfigs Artifact - inputs: - PathtoPublish: '$(Build.StagingDirectory)/ReleaseConfigs.txt' - PublishLocation: Container - ArtifactName: ReleaseConfigs - - - task: powershell@2 - displayName: Check if SymbolPublishingExclusionsFile.txt exists - inputs: - targetType: inline - script: | - $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" - if(Test-Path -Path $symbolExclusionfile) - { - Write-Host "SymbolExclusionFile exists" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]true" - } - else{ - Write-Host "Symbols Exclusion file does not exists" - Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]false" - } - - - task: PublishBuildArtifacts@1 - displayName: Publish SymbolPublishingExclusionsFile Artifact - condition: eq(variables['SymbolExclusionFile'], 'true') - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' - PublishLocation: Container - ArtifactName: ReleaseConfigs - - - ${{ if eq(parameters.publishAssetsImmediately, 'true') }}: - - template: /eng/common/templates/post-build/setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: AzureCLI@2 - displayName: Publish Using Darc - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) - -PublishingInfraVersion 3 - -AzdoToken '$(System.AccessToken)' - -WaitPublishingFinish true - -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' - -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' +- template: /eng/common/core-templates/job/publish-build-assets.yml + parameters: + is1ESPipeline: false - - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - - template: /eng/common/templates/steps/publish-logs.yml - parameters: - JobLabel: 'Publish_Artifacts_Logs' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/job/source-build.yml b/eng/common/templates/job/source-build.yml index c0ff472b697..e44d47b1d76 100644 --- a/eng/common/templates/job/source-build.yml +++ b/eng/common/templates/job/source-build.yml @@ -1,74 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. The template produces a server job with a - # default ID 'Source_Build_Complete' to put in a dependency list if necessary. - - # Specifies the prefix for source-build jobs added to pipeline. Use this if disambiguation needed. - jobNamePrefix: 'Source_Build' - - # Defines the platform on which to run the job. By default, a linux-x64 machine, suitable for - # managed-only repositories. This is an object with these properties: - # - # name: '' - # The name of the job. This is included in the job ID. - # targetRID: '' - # The name of the target RID to use, instead of the one auto-detected by Arcade. - # nonPortable: false - # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than - # linux-x64), and compiling against distro-provided packages rather than portable ones. - # skipPublishValidation: false - # Disables publishing validation. By default, a check is performed to ensure no packages are - # published by source-build. - # container: '' - # A container to use. Runs in docker. - # pool: {} - # A pool to use. Runs directly on an agent. - # buildScript: '' - # Specifies the build script to invoke to perform the build in the repo. The default - # './build.sh' should work for typical Arcade repositories, but this is customizable for - # difficult situations. - # jobProperties: {} - # A list of job properties to inject at the top level, for potential extensibility beyond - # container and pool. - platform: {} - - # If set to true and running on a non-public project, - # Internal blob storage locations will be enabled. - # This is not enabled by default because many repositories do not need internal sources - # and do not need to have the required service connections approved in the pipeline. - enableInternalSources: false - jobs: -- job: ${{ parameters.jobNamePrefix }}_${{ parameters.platform.name }} - displayName: Source-Build (${{ parameters.platform.name }}) - - ${{ each property in parameters.platform.jobProperties }}: - ${{ property.key }}: ${{ property.value }} - - ${{ if ne(parameters.platform.container, '') }}: - container: ${{ parameters.platform.container }} - - ${{ if eq(parameters.platform.pool, '') }}: - # The default VM host AzDO pool. This should be capable of running Docker containers: almost all - # source-build builds run in Docker, including the default managed platform. - # /eng/common/templates/variables/pool-providers.yml can't be used here (some customers declare variables already), so duplicate its logic - pool: - ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore-Svc-Public' ), False, 'NetCore-Public')] - demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open - - ${{ if eq(variables['System.TeamProject'], 'internal') }}: - name: $[replace(replace(eq(contains(coalesce(variables['System.PullRequest.TargetBranch'], variables['Build.SourceBranch'], 'refs/heads/main'), 'release'), 'true'), True, 'NetCore1ESPool-Svc-Internal'), False, 'NetCore1ESPool-Internal')] - demands: ImageOverride -equals Build.Ubuntu.1804.Amd64 - - ${{ if ne(parameters.platform.pool, '') }}: - pool: ${{ parameters.platform.pool }} - - workspace: - clean: all +- template: /eng/common/core-templates/job/source-build.yml + parameters: + is1ESPipeline: false - steps: - - ${{ if eq(parameters.enableInternalSources, true) }}: - - template: /eng/common/templates/steps/enable-internal-runtimes.yml - - template: /eng/common/templates/steps/source-build.yml - parameters: - platform: ${{ parameters.platform }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/job/source-index-stage1.yml b/eng/common/templates/job/source-index-stage1.yml index 0b6bb89dc78..89f3291593c 100644 --- a/eng/common/templates/job/source-index-stage1.yml +++ b/eng/common/templates/job/source-index-stage1.yml @@ -1,82 +1,7 @@ -parameters: - runAsPublic: false - sourceIndexUploadPackageVersion: 2.0.0-20240502.12 - sourceIndexProcessBinlogPackageVersion: 1.0.1-20240129.2 - sourceIndexPackageSource: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json - sourceIndexBuildCommand: powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "eng/common/build.ps1 -restore -build -binarylog -ci" - preSteps: [] - binlogPath: artifacts/log/Debug/Build.binlog - condition: '' - dependsOn: '' - pool: '' - jobs: -- job: SourceIndexStage1 - dependsOn: ${{ parameters.dependsOn }} - condition: ${{ parameters.condition }} - variables: - - name: SourceIndexUploadPackageVersion - value: ${{ parameters.sourceIndexUploadPackageVersion }} - - name: SourceIndexProcessBinlogPackageVersion - value: ${{ parameters.sourceIndexProcessBinlogPackageVersion }} - - name: SourceIndexPackageSource - value: ${{ parameters.sourceIndexPackageSource }} - - name: BinlogPath - value: ${{ parameters.binlogPath }} - - template: /eng/common/templates/variables/pool-providers.yml - - ${{ if ne(parameters.pool, '') }}: - pool: ${{ parameters.pool }} - ${{ if eq(parameters.pool, '') }}: - pool: - ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: $(DncEngPublicBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64.open - ${{ if eq(variables['System.TeamProject'], 'internal') }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - - steps: - - ${{ each preStep in parameters.preSteps }}: - - ${{ preStep }} - - - task: UseDotNet@2 - displayName: Use .NET 8 SDK - inputs: - packageType: sdk - version: 8.0.x - installationPath: $(Agent.TempDirectory)/dotnet - workingDirectory: $(Agent.TempDirectory) - - - script: | - $(Agent.TempDirectory)/dotnet/dotnet tool install BinLogToSln --version $(sourceIndexProcessBinlogPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - $(Agent.TempDirectory)/dotnet/dotnet tool install UploadIndexStage1 --version $(sourceIndexUploadPackageVersion) --add-source $(SourceIndexPackageSource) --tool-path $(Agent.TempDirectory)/.source-index/tools - displayName: Download Tools - # Set working directory to temp directory so 'dotnet' doesn't try to use global.json and use the repo's sdk. - workingDirectory: $(Agent.TempDirectory) - - - script: ${{ parameters.sourceIndexBuildCommand }} - displayName: Build Repository - - - script: $(Agent.TempDirectory)/.source-index/tools/BinLogToSln -i $(BinlogPath) -r $(Build.SourcesDirectory) -n $(Build.Repository.Name) -o .source-index/stage1output - displayName: Process Binlog into indexable sln - - - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - task: AzureCLI@2 - displayName: Get stage 1 auth token - inputs: - azureSubscription: 'SourceDotNet Stage1 Publish' - addSpnToEnvironment: true - scriptType: 'ps' - scriptLocation: 'inlineScript' - inlineScript: | - echo "##vso[task.setvariable variable=ARM_CLIENT_ID;issecret=true]$env:servicePrincipalId" - echo "##vso[task.setvariable variable=ARM_ID_TOKEN;issecret=true]$env:idToken" - echo "##vso[task.setvariable variable=ARM_TENANT_ID;issecret=true]$env:tenantId" - - - script: | - az login --service-principal -u $(ARM_CLIENT_ID) --tenant $(ARM_TENANT_ID) --allow-no-subscriptions --federated-token $(ARM_ID_TOKEN) - displayName: "Login to Azure" +- template: /eng/common/core-templates/job/source-index-stage1.yml + parameters: + is1ESPipeline: false - - script: $(Agent.TempDirectory)/.source-index/tools/UploadIndexStage1 -i .source-index/stage1output -n $(Build.Repository.Name) -s netsourceindexstage1 -b stage1 - displayName: Upload stage1 artifacts to source index + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/jobs/codeql-build.yml b/eng/common/templates/jobs/codeql-build.yml index f7dc5ea4aaa..517f24d6a52 100644 --- a/eng/common/templates/jobs/codeql-build.yml +++ b/eng/common/templates/jobs/codeql-build.yml @@ -1,31 +1,7 @@ -parameters: - # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md - continueOnError: false - # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - jobs: [] - # Optional: if specified, restore and use this version of Guardian instead of the default. - overrideGuardianVersion: '' - jobs: -- template: /eng/common/templates/jobs/jobs.yml +- template: /eng/common/core-templates/jobs/codeql-build.yml parameters: - enableMicrobuild: false - enablePublishBuildArtifacts: false - enablePublishTestResults: false - enablePublishBuildAssets: false - enablePublishUsingPipelines: false - enableTelemetry: true + is1ESPipeline: false - variables: - - group: Publish-Build-Assets - # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in - # sync with the packages.config file. - - name: DefaultGuardianVersion - value: 0.109.0 - - name: GuardianPackagesConfigFile - value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config - - name: GuardianVersion - value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} - - jobs: ${{ parameters.jobs }} - + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/jobs/jobs.yml b/eng/common/templates/jobs/jobs.yml index 289bb2396ce..388e9037b3e 100644 --- a/eng/common/templates/jobs/jobs.yml +++ b/eng/common/templates/jobs/jobs.yml @@ -1,97 +1,7 @@ -parameters: - # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md - continueOnError: false - - # Optional: Include PublishBuildArtifacts task - enablePublishBuildArtifacts: false - - # Optional: Enable publishing using release pipelines - enablePublishUsingPipelines: false - - # Optional: Enable running the source-build jobs to build repo from source - enableSourceBuild: false - - # Optional: Parameters for source-build template. - # See /eng/common/templates/jobs/source-build.yml for options - sourceBuildParameters: [] - - graphFileGeneration: - # Optional: Enable generating the graph files at the end of the build - enabled: false - # Optional: Include toolset dependencies in the generated graph files - includeToolset: false - - # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job - jobs: [] - - # Optional: Override automatically derived dependsOn value for "publish build assets" job - publishBuildAssetsDependsOn: '' - - # Optional: Publish the assets as soon as the publish to BAR stage is complete, rather doing so in a separate stage. - publishAssetsImmediately: false - - # Optional: If using publishAssetsImmediately and additional parameters are needed, can be used to send along additional parameters (normally sent to post-build.yml) - artifactsPublishingAdditionalParameters: '' - signingValidationAdditionalParameters: '' - - # Optional: should run as a public build even in the internal project - # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. - runAsPublic: false - - enableSourceIndex: false - sourceIndexParams: {} - -# Internal resources (telemetry, microbuild) can only be accessed from non-public projects, -# and some (Microbuild) should only be applied to non-PR cases for internal builds. - jobs: -- ${{ each job in parameters.jobs }}: - - template: ../job/job.yml - parameters: - # pass along parameters - ${{ each parameter in parameters }}: - ${{ if ne(parameter.key, 'jobs') }}: - ${{ parameter.key }}: ${{ parameter.value }} - - # pass along job properties - ${{ each property in job }}: - ${{ if ne(property.key, 'job') }}: - ${{ property.key }}: ${{ property.value }} - - name: ${{ job.job }} - -- ${{ if eq(parameters.enableSourceBuild, true) }}: - - template: /eng/common/templates/jobs/source-build.yml - parameters: - allCompletedJobId: Source_Build_Complete - ${{ each parameter in parameters.sourceBuildParameters }}: - ${{ parameter.key }}: ${{ parameter.value }} - -- ${{ if eq(parameters.enableSourceIndex, 'true') }}: - - template: ../job/source-index-stage1.yml - parameters: - runAsPublic: ${{ parameters.runAsPublic }} - ${{ each parameter in parameters.sourceIndexParams }}: - ${{ parameter.key }}: ${{ parameter.value }} - -- ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - - ${{ if or(eq(parameters.enablePublishBuildAssets, true), eq(parameters.artifacts.publish.manifests, 'true'), ne(parameters.artifacts.publish.manifests, '')) }}: - - template: ../job/publish-build-assets.yml - parameters: - continueOnError: ${{ parameters.continueOnError }} - dependsOn: - - ${{ if ne(parameters.publishBuildAssetsDependsOn, '') }}: - - ${{ each job in parameters.publishBuildAssetsDependsOn }}: - - ${{ job.job }} - - ${{ if eq(parameters.publishBuildAssetsDependsOn, '') }}: - - ${{ each job in parameters.jobs }}: - - ${{ job.job }} - - ${{ if eq(parameters.enableSourceBuild, true) }}: - - Source_Build_Complete +- template: /eng/common/core-templates/jobs/jobs.yml + parameters: + is1ESPipeline: false - runAsPublic: ${{ parameters.runAsPublic }} - publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} - publishAssetsImmediately: ${{ parameters.publishAssetsImmediately }} - enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - signingValidationAdditionalParameters: ${{ parameters.signingValidationAdditionalParameters }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/jobs/source-build.yml b/eng/common/templates/jobs/source-build.yml index 5f46bfa895c..818d4c326db 100644 --- a/eng/common/templates/jobs/source-build.yml +++ b/eng/common/templates/jobs/source-build.yml @@ -1,54 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. A job is created for each platform, as - # well as an optional server job that completes when all platform jobs complete. - - # The name of the "join" job for all source-build platforms. If set to empty string, the job is - # not included. Existing repo pipelines can use this job depend on all source-build jobs - # completing without maintaining a separate list of every single job ID: just depend on this one - # server job. By default, not included. Recommended name if used: 'Source_Build_Complete'. - allCompletedJobId: '' - - # See /eng/common/templates/job/source-build.yml - jobNamePrefix: 'Source_Build' - - # This is the default platform provided by Arcade, intended for use by a managed-only repo. - defaultManagedPlatform: - name: 'Managed' - container: 'mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream8' - - # Defines the platforms on which to run build jobs. One job is created for each platform, and the - # object in this array is sent to the job template as 'platform'. If no platforms are specified, - # one job runs on 'defaultManagedPlatform'. - platforms: [] - - # If set to true and running on a non-public project, - # Internal nuget and blob storage locations will be enabled. - # This is not enabled by default because many repositories do not need internal sources - # and do not need to have the required service connections approved in the pipeline. - enableInternalSources: false - jobs: +- template: /eng/common/core-templates/jobs/source-build.yml + parameters: + is1ESPipeline: false -- ${{ if ne(parameters.allCompletedJobId, '') }}: - - job: ${{ parameters.allCompletedJobId }} - displayName: Source-Build Complete - pool: server - dependsOn: - - ${{ each platform in parameters.platforms }}: - - ${{ parameters.jobNamePrefix }}_${{ platform.name }} - - ${{ if eq(length(parameters.platforms), 0) }}: - - ${{ parameters.jobNamePrefix }}_${{ parameters.defaultManagedPlatform.name }} - -- ${{ each platform in parameters.platforms }}: - - template: /eng/common/templates/job/source-build.yml - parameters: - jobNamePrefix: ${{ parameters.jobNamePrefix }} - platform: ${{ platform }} - enableInternalSources: ${{ parameters.enableInternalSources }} - -- ${{ if eq(length(parameters.platforms), 0) }}: - - template: /eng/common/templates/job/source-build.yml - parameters: - jobNamePrefix: ${{ parameters.jobNamePrefix }} - platform: ${{ parameters.defaultManagedPlatform }} - enableInternalSources: ${{ parameters.enableInternalSources }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/common-variables.yml b/eng/common/templates/post-build/common-variables.yml index 173914f2364..7fa10587559 100644 --- a/eng/common/templates/post-build/common-variables.yml +++ b/eng/common/templates/post-build/common-variables.yml @@ -1,22 +1,8 @@ variables: - - group: Publish-Build-Assets +- template: /eng/common/core-templates/post-build/common-variables.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: false - # Whether the build is internal or not - - name: IsInternalBuild - value: ${{ and(ne(variables['System.TeamProject'], 'public'), contains(variables['Build.SourceBranch'], 'internal')) }} - - # Default Maestro++ API Endpoint and API Version - - name: MaestroApiEndPoint - value: "https://maestro.dot.net" - - name: MaestroApiAccessToken - value: $(MaestroAccessToken) - - name: MaestroApiVersion - value: "2020-02-20" - - - name: SourceLinkCLIVersion - value: 3.0.0 - - name: SymbolToolVersion - value: 1.0.1 - - - name: runCodesignValidationInjection - value: false + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/post-build.yml b/eng/common/templates/post-build/post-build.yml index c3b6a3012fe..53ede714bdd 100644 --- a/eng/common/templates/post-build/post-build.yml +++ b/eng/common/templates/post-build/post-build.yml @@ -1,283 +1,8 @@ -parameters: - # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST. - # Publishing V1 is no longer supported - # Publishing V2 is no longer supported - # Publishing V3 is the default - - name: publishingInfraVersion - displayName: Which version of publishing should be used to promote the build definition? - type: number - default: 3 - values: - - 3 - - - name: BARBuildId - displayName: BAR Build Id - type: number - default: 0 - - - name: PromoteToChannelIds - displayName: Channel to promote BARBuildId to - type: string - default: '' - - - name: enableSourceLinkValidation - displayName: Enable SourceLink validation - type: boolean - default: false - - - name: enableSigningValidation - displayName: Enable signing validation - type: boolean - default: true - - - name: enableSymbolValidation - displayName: Enable symbol validation - type: boolean - default: false - - - name: enableNugetValidation - displayName: Enable NuGet validation - type: boolean - default: true - - - name: publishInstallersAndChecksums - displayName: Publish installers and checksums - type: boolean - default: true - - - name: SDLValidationParameters - type: object - default: - enable: false - publishGdn: false - continueOnError: false - params: '' - artifactNames: '' - downloadArtifacts: true - - # These parameters let the user customize the call to sdk-task.ps1 for publishing - # symbols & general artifacts as well as for signing validation - - name: symbolPublishingAdditionalParameters - displayName: Symbol publishing additional parameters - type: string - default: '' - - - name: artifactsPublishingAdditionalParameters - displayName: Artifact publishing additional parameters - type: string - default: '' - - - name: signingValidationAdditionalParameters - displayName: Signing validation additional parameters - type: string - default: '' - - # Which stages should finish execution before post-build stages start - - name: validateDependsOn - type: object - default: - - build - - - name: publishDependsOn - type: object - default: - - Validate - - # Optional: Call asset publishing rather than running in a separate stage - - name: publishAssetsImmediately - type: boolean - default: false - stages: -- ${{ if or(eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - - stage: Validate - dependsOn: ${{ parameters.validateDependsOn }} - displayName: Validate Build Assets - variables: - - template: common-variables.yml - - template: /eng/common/templates/variables/pool-providers.yml - jobs: - - job: - displayName: NuGet Validation - condition: and(succeededOrFailed(), eq( ${{ parameters.enableNugetValidation }}, 'true')) - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Package Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: PackageArtifacts - checkDownloadedFiles: true - - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/nuget-validation.ps1 - arguments: -PackagesPath $(Build.ArtifactStagingDirectory)/PackageArtifacts/ - -ToolDestinationPath $(Agent.BuildDirectory)/Extract/ - - - job: - displayName: Signing Validation - condition: and( eq( ${{ parameters.enableSigningValidation }}, 'true'), ne( variables['PostBuildSign'], 'true')) - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Package Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: PackageArtifacts - checkDownloadedFiles: true - itemPattern: | - ** - !**/Microsoft.SourceBuild.Intermediate.*.nupkg - - # This is necessary whenever we want to publish/restore to an AzDO private feed - # Since sdk-task.ps1 tries to restore packages we need to do this authentication here - # otherwise it'll complain about accessing a private feed. - - task: NuGetAuthenticate@1 - displayName: 'Authenticate to AzDO Feeds' - - # Signing validation will optionally work with the buildmanifest file which is downloaded from - # Azure DevOps above. - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task SigningValidation -restore -msbuildEngine vs - /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts' - /p:SignCheckExclusionsFile='$(Build.SourcesDirectory)/eng/SignCheckExclusionsFile.txt' - ${{ parameters.signingValidationAdditionalParameters }} - - - template: ../steps/publish-logs.yml - parameters: - StageLabel: 'Validation' - JobLabel: 'Signing' - - - job: - displayName: SourceLink Validation - condition: eq( ${{ parameters.enableSourceLinkValidation }}, 'true') - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ else }}: - name: $(DncEngInternalBuildPool) - demands: ImageOverride -equals windows.vs2019.amd64 - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: DownloadBuildArtifacts@0 - displayName: Download Blob Artifacts - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - artifactName: BlobArtifacts - checkDownloadedFiles: true - - - task: PowerShell@2 - displayName: Validate - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/sourcelink-validation.ps1 - arguments: -InputPath $(Build.ArtifactStagingDirectory)/BlobArtifacts/ - -ExtractPath $(Agent.BuildDirectory)/Extract/ - -GHRepoName $(Build.Repository.Name) - -GHCommit $(Build.SourceVersion) - -SourcelinkCliVersion $(SourceLinkCLIVersion) - continueOnError: true - - - template: /eng/common/templates/job/execute-sdl.yml - parameters: - enable: ${{ parameters.SDLValidationParameters.enable }} - publishGuardianDirectoryToPipeline: ${{ parameters.SDLValidationParameters.publishGdn }} - additionalParameters: ${{ parameters.SDLValidationParameters.params }} - continueOnError: ${{ parameters.SDLValidationParameters.continueOnError }} - artifactNames: ${{ parameters.SDLValidationParameters.artifactNames }} - downloadArtifacts: ${{ parameters.SDLValidationParameters.downloadArtifacts }} - -- ${{ if ne(parameters.publishAssetsImmediately, 'true') }}: - - stage: publish_using_darc - ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - dependsOn: ${{ parameters.publishDependsOn }} - ${{ else }}: - dependsOn: ${{ parameters.validateDependsOn }} - displayName: Publish using Darc - variables: - - template: common-variables.yml - - template: /eng/common/templates/variables/pool-providers.yml - jobs: - - job: - displayName: Publish Using Darc - timeoutInMinutes: 120 - pool: - # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com) - ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}: - name: VSEngSS-MicroBuild2022-1ES - demands: Cmd - # If it's not devdiv, it's dnceng - ${{ else }}: - name: NetCore1ESPool-Publishing-Internal - demands: ImageOverride -equals windows.vs2019.amd64 - steps: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - task: NuGetAuthenticate@1 +- template: /eng/common/core-templates/post-build/post-build.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: false - - task: AzureCLI@2 - displayName: Publish Using Darc - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: ps - scriptLocation: scriptPath - scriptPath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) - -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} - -AzdoToken '$(System.AccessToken)' - -WaitPublishingFinish true - -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' - -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/setup-maestro-vars.yml b/eng/common/templates/post-build/setup-maestro-vars.yml index 64b9abc6850..a79fab5b441 100644 --- a/eng/common/templates/post-build/setup-maestro-vars.yml +++ b/eng/common/templates/post-build/setup-maestro-vars.yml @@ -1,70 +1,8 @@ -parameters: - BARBuildId: '' - PromoteToChannelIds: '' - steps: - - ${{ if eq(coalesce(parameters.PromoteToChannelIds, 0), 0) }}: - - task: DownloadBuildArtifacts@0 - displayName: Download Release Configs - inputs: - buildType: current - artifactName: ReleaseConfigs - checkDownloadedFiles: true - - - task: AzureCLI@2 - name: setReleaseVars - displayName: Set Release Configs Vars - inputs: - azureSubscription: "Darc: Maestro Production" - scriptType: pscore - scriptLocation: inlineScript - inlineScript: | - try { - if (!$Env:PromoteToMaestroChannels -or $Env:PromoteToMaestroChannels.Trim() -eq '') { - $Content = Get-Content $(Build.StagingDirectory)/ReleaseConfigs/ReleaseConfigs.txt - - $BarId = $Content | Select -Index 0 - $Channels = $Content | Select -Index 1 - $IsStableBuild = $Content | Select -Index 2 - - $AzureDevOpsProject = $Env:System_TeamProject - $AzureDevOpsBuildDefinitionId = $Env:System_DefinitionId - $AzureDevOpsBuildId = $Env:Build_BuildId - } - else { - . $(Build.SourcesDirectory)\eng\common\tools.ps1 - $darc = Get-Darc - $buildInfo = & $darc get-build ` - --id ${{ parameters.BARBuildId }} ` - --extended ` - --output-format json ` - --ci ` - | convertFrom-Json - - $BarId = ${{ parameters.BARBuildId }} - $Channels = $Env:PromoteToMaestroChannels -split "," - $Channels = $Channels -join "][" - $Channels = "[$Channels]" - - $IsStableBuild = $buildInfo.stable - $AzureDevOpsProject = $buildInfo.azureDevOpsProject - $AzureDevOpsBuildDefinitionId = $buildInfo.azureDevOpsBuildDefinitionId - $AzureDevOpsBuildId = $buildInfo.azureDevOpsBuildId - } - - Write-Host "##vso[task.setvariable variable=BARBuildId]$BarId" - Write-Host "##vso[task.setvariable variable=TargetChannels]$Channels" - Write-Host "##vso[task.setvariable variable=IsStableBuild]$IsStableBuild" +- template: /eng/common/core-templates/post-build/setup-maestro-vars.yml + parameters: + # Specifies whether to use 1ES + is1ESPipeline: false - Write-Host "##vso[task.setvariable variable=AzDOProjectName]$AzureDevOpsProject" - Write-Host "##vso[task.setvariable variable=AzDOPipelineId]$AzureDevOpsBuildDefinitionId" - Write-Host "##vso[task.setvariable variable=AzDOBuildId]$AzureDevOpsBuildId" - } - catch { - Write-Host $_ - Write-Host $_.Exception - Write-Host $_.ScriptStackTrace - exit 1 - } - env: - PromoteToMaestroChannels: ${{ parameters.PromoteToChannelIds }} + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/post-build/trigger-subscription.yml b/eng/common/templates/post-build/trigger-subscription.yml deleted file mode 100644 index da669030daf..00000000000 --- a/eng/common/templates/post-build/trigger-subscription.yml +++ /dev/null @@ -1,13 +0,0 @@ -parameters: - ChannelId: 0 - -steps: -- task: PowerShell@2 - displayName: Triggering subscriptions - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/trigger-subscriptions.ps1 - arguments: -SourceRepo $(Build.Repository.Uri) - -ChannelId ${{ parameters.ChannelId }} - -MaestroApiAccessToken $(MaestroAccessToken) - -MaestroApiEndPoint $(MaestroApiEndPoint) - -MaestroApiVersion $(MaestroApiVersion) diff --git a/eng/common/templates/steps/add-build-to-channel.yml b/eng/common/templates/steps/add-build-to-channel.yml deleted file mode 100644 index f67a210d62f..00000000000 --- a/eng/common/templates/steps/add-build-to-channel.yml +++ /dev/null @@ -1,13 +0,0 @@ -parameters: - ChannelId: 0 - -steps: -- task: PowerShell@2 - displayName: Add Build to Channel - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/add-build-to-channel.ps1 - arguments: -BuildId $(BARBuildId) - -ChannelId ${{ parameters.ChannelId }} - -MaestroApiAccessToken $(MaestroApiAccessToken) - -MaestroApiEndPoint $(MaestroApiEndPoint) - -MaestroApiVersion $(MaestroApiVersion) diff --git a/eng/common/templates/steps/build-reason.yml b/eng/common/templates/steps/build-reason.yml deleted file mode 100644 index eba58109b52..00000000000 --- a/eng/common/templates/steps/build-reason.yml +++ /dev/null @@ -1,12 +0,0 @@ -# build-reason.yml -# Description: runs steps if build.reason condition is valid. conditions is a string of valid build reasons -# to include steps (',' separated). -parameters: - conditions: '' - steps: [] - -steps: - - ${{ if and( not(startsWith(parameters.conditions, 'not')), contains(parameters.conditions, variables['build.reason'])) }}: - - ${{ parameters.steps }} - - ${{ if and( startsWith(parameters.conditions, 'not'), not(contains(parameters.conditions, variables['build.reason']))) }}: - - ${{ parameters.steps }} diff --git a/eng/common/templates/steps/component-governance.yml b/eng/common/templates/steps/component-governance.yml index cbba0596709..c12a5f8d21d 100644 --- a/eng/common/templates/steps/component-governance.yml +++ b/eng/common/templates/steps/component-governance.yml @@ -1,13 +1,7 @@ -parameters: - disableComponentGovernance: false - componentGovernanceIgnoreDirectories: '' - steps: -- ${{ if eq(parameters.disableComponentGovernance, 'true') }}: - - script: echo "##vso[task.setvariable variable=skipComponentGovernanceDetection]true" - displayName: Set skipComponentGovernanceDetection variable -- ${{ if ne(parameters.disableComponentGovernance, 'true') }}: - - task: ComponentGovernanceComponentDetection@0 - continueOnError: true - inputs: - ignoreDirectories: ${{ parameters.componentGovernanceIgnoreDirectories }} \ No newline at end of file +- template: /eng/common/core-templates/steps/component-governance.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/enable-internal-runtimes.yml b/eng/common/templates/steps/enable-internal-runtimes.yml index 54dc9416c51..b21a8038cc1 100644 --- a/eng/common/templates/steps/enable-internal-runtimes.yml +++ b/eng/common/templates/steps/enable-internal-runtimes.yml @@ -1,28 +1,10 @@ # Obtains internal runtime download credentials and populates the 'dotnetbuilds-internal-container-read-token-base64' # variable with the base64-encoded SAS token, by default -parameters: -- name: federatedServiceConnection - type: string - default: 'dotnetbuilds-internal-read' -- name: outputVariableName - type: string - default: 'dotnetbuilds-internal-container-read-token-base64' -- name: expiryInHours - type: number - default: 1 -- name: base64Encode - type: boolean - default: true - steps: -- ${{ if ne(variables['System.TeamProject'], 'public') }}: - - template: /eng/common/templates/steps/get-delegation-sas.yml - parameters: - federatedServiceConnection: ${{ parameters.federatedServiceConnection }} - outputVariableName: ${{ parameters.outputVariableName }} - expiryInHours: ${{ parameters.expiryInHours }} - base64Encode: ${{ parameters.base64Encode }} - storageAccount: dotnetbuilds - container: internal - permissions: rl +- template: /eng/common/core-templates/steps/enable-internal-runtimes.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/enable-internal-sources.yml b/eng/common/templates/steps/enable-internal-sources.yml new file mode 100644 index 00000000000..5f87e9abb8a --- /dev/null +++ b/eng/common/templates/steps/enable-internal-sources.yml @@ -0,0 +1,7 @@ +steps: +- template: /eng/common/core-templates/steps/enable-internal-sources.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/steps/execute-codeql.yml b/eng/common/templates/steps/execute-codeql.yml deleted file mode 100644 index 3930b163021..00000000000 --- a/eng/common/templates/steps/execute-codeql.yml +++ /dev/null @@ -1,32 +0,0 @@ -parameters: - # Language that should be analyzed. Defaults to csharp - language: csharp - # Build Commands - buildCommands: '' - overrideParameters: '' # Optional: to override values for parameters. - additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' - # Optional: if specified, restore and use this version of Guardian instead of the default. - overrideGuardianVersion: '' - # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth - # diagnosis of problems with specific tool configurations. - publishGuardianDirectoryToPipeline: false - # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL - # parameters rather than relying on YAML. It may be better to use a local script, because you can - # reproduce results locally without piecing together a command based on the YAML. - executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' - # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named - # 'continueOnError', the parameter value is not correctly picked up. - # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter - # optional: determines whether to continue the build if the step errors; - sdlContinueOnError: false - -steps: -- template: /eng/common/templates/steps/execute-sdl.yml - parameters: - overrideGuardianVersion: ${{ parameters.overrideGuardianVersion }} - executeAllSdlToolsScript: ${{ parameters.executeAllSdlToolsScript }} - overrideParameters: ${{ parameters.overrideParameters }} - additionalParameters: '${{ parameters.additionalParameters }} - -CodeQLAdditionalRunConfigParams @("BuildCommands < ${{ parameters.buildCommands }}", "Language < ${{ parameters.language }}")' - publishGuardianDirectoryToPipeline: ${{ parameters.publishGuardianDirectoryToPipeline }} - sdlContinueOnError: ${{ parameters.sdlContinueOnError }} \ No newline at end of file diff --git a/eng/common/templates/steps/execute-sdl.yml b/eng/common/templates/steps/execute-sdl.yml deleted file mode 100644 index fe0ebf8c904..00000000000 --- a/eng/common/templates/steps/execute-sdl.yml +++ /dev/null @@ -1,89 +0,0 @@ -parameters: - overrideGuardianVersion: '' - executeAllSdlToolsScript: '' - overrideParameters: '' - additionalParameters: '' - publishGuardianDirectoryToPipeline: false - sdlContinueOnError: false - condition: '' - -steps: -- task: NuGetAuthenticate@1 - -- task: NuGetToolInstaller@1 - displayName: 'Install NuGet.exe' - -- ${{ if ne(parameters.overrideGuardianVersion, '') }}: - - pwsh: | - Set-Location -Path $(Build.SourcesDirectory)\eng\common\sdl - . .\sdl.ps1 - $guardianCliLocation = Install-Gdn -Path $(Build.SourcesDirectory)\.artifacts -Version ${{ parameters.overrideGuardianVersion }} - Write-Host "##vso[task.setvariable variable=GuardianCliLocation]$guardianCliLocation" - displayName: Install Guardian (Overridden) - -- ${{ if eq(parameters.overrideGuardianVersion, '') }}: - - pwsh: | - Set-Location -Path $(Build.SourcesDirectory)\eng\common\sdl - . .\sdl.ps1 - $guardianCliLocation = Install-Gdn -Path $(Build.SourcesDirectory)\.artifacts - Write-Host "##vso[task.setvariable variable=GuardianCliLocation]$guardianCliLocation" - displayName: Install Guardian - -- ${{ if ne(parameters.overrideParameters, '') }}: - - powershell: ${{ parameters.executeAllSdlToolsScript }} ${{ parameters.overrideParameters }} - displayName: Execute SDL (Overridden) - continueOnError: ${{ parameters.sdlContinueOnError }} - condition: ${{ parameters.condition }} - env: - GUARDIAN_DEFAULT_PACKAGE_SOURCE_SECRET: $(System.AccessToken) - -- ${{ if eq(parameters.overrideParameters, '') }}: - - powershell: ${{ parameters.executeAllSdlToolsScript }} - -GuardianCliLocation $(GuardianCliLocation) - -NugetPackageDirectory $(Build.SourcesDirectory)\.packages - ${{ parameters.additionalParameters }} - displayName: Execute SDL - continueOnError: ${{ parameters.sdlContinueOnError }} - condition: ${{ parameters.condition }} - env: - GUARDIAN_DEFAULT_PACKAGE_SOURCE_SECRET: $(System.AccessToken) - -- ${{ if ne(parameters.publishGuardianDirectoryToPipeline, 'false') }}: - # We want to publish the Guardian results and configuration for easy diagnosis. However, the - # '.gdn' dir is a mix of configuration, results, extracted dependencies, and Guardian default - # tooling files. Some of these files are large and aren't useful during an investigation, so - # exclude them by simply deleting them before publishing. (As of writing, there is no documented - # way to selectively exclude a dir from the pipeline artifact publish task.) - - task: DeleteFiles@1 - displayName: Delete Guardian dependencies to avoid uploading - inputs: - SourceFolder: $(Agent.BuildDirectory)/.gdn - Contents: | - c - i - condition: succeededOrFailed() - - - publish: $(Agent.BuildDirectory)/.gdn - artifact: GuardianConfiguration - displayName: Publish GuardianConfiguration - condition: succeededOrFailed() - - # Publish the SARIF files in a container named CodeAnalysisLogs to enable integration - # with the "SARIF SAST Scans Tab" Azure DevOps extension - - task: CopyFiles@2 - displayName: Copy SARIF files - inputs: - flattenFolders: true - sourceFolder: $(Agent.BuildDirectory)/.gdn/rc/ - contents: '**/*.sarif' - targetFolder: $(Build.SourcesDirectory)/CodeAnalysisLogs - condition: succeededOrFailed() - - # Use PublishBuildArtifacts because the SARIF extension only checks this case - # see microsoft/sarif-azuredevops-extension#4 - - task: PublishBuildArtifacts@1 - displayName: Publish SARIF files to CodeAnalysisLogs container - inputs: - pathToPublish: $(Build.SourcesDirectory)/CodeAnalysisLogs - artifactName: CodeAnalysisLogs - condition: succeededOrFailed() \ No newline at end of file diff --git a/eng/common/templates/steps/generate-sbom.yml b/eng/common/templates/steps/generate-sbom.yml index 2b21eae4273..26dc00a2e0f 100644 --- a/eng/common/templates/steps/generate-sbom.yml +++ b/eng/common/templates/steps/generate-sbom.yml @@ -1,48 +1,7 @@ -# BuildDropPath - The root folder of the drop directory for which the manifest file will be generated. -# PackageName - The name of the package this SBOM represents. -# PackageVersion - The version of the package this SBOM represents. -# ManifestDirPath - The path of the directory where the generated manifest files will be placed -# IgnoreDirectories - Directories to ignore for SBOM generation. This will be passed through to the CG component detector. - -parameters: - PackageVersion: 8.0.0 - BuildDropPath: '$(Build.SourcesDirectory)/artifacts' - PackageName: '.NET' - ManifestDirPath: $(Build.ArtifactStagingDirectory)/sbom - IgnoreDirectories: '' - sbomContinueOnError: true - steps: -- task: PowerShell@2 - displayName: Prep for SBOM generation in (Non-linux) - condition: or(eq(variables['Agent.Os'], 'Windows_NT'), eq(variables['Agent.Os'], 'Darwin')) - inputs: - filePath: ./eng/common/generate-sbom-prep.ps1 - arguments: ${{parameters.manifestDirPath}} - -# Chmodding is a workaround for https://github.com/dotnet/arcade/issues/8461 -- script: | - chmod +x ./eng/common/generate-sbom-prep.sh - ./eng/common/generate-sbom-prep.sh ${{parameters.manifestDirPath}} - displayName: Prep for SBOM generation in (Linux) - condition: eq(variables['Agent.Os'], 'Linux') - continueOnError: ${{ parameters.sbomContinueOnError }} - -- task: AzureArtifacts.manifest-generator-task.manifest-generator-task.ManifestGeneratorTask@0 - displayName: 'Generate SBOM manifest' - continueOnError: ${{ parameters.sbomContinueOnError }} - inputs: - PackageName: ${{ parameters.packageName }} - BuildDropPath: ${{ parameters.buildDropPath }} - PackageVersion: ${{ parameters.packageVersion }} - ManifestDirPath: ${{ parameters.manifestDirPath }} - ${{ if ne(parameters.IgnoreDirectories, '') }}: - AdditionalComponentDetectorArgs: '--IgnoreDirectories ${{ parameters.IgnoreDirectories }}' - -- task: PublishPipelineArtifact@1 - displayName: Publish SBOM manifest - continueOnError: ${{parameters.sbomContinueOnError}} - inputs: - targetPath: '${{parameters.manifestDirPath}}' - artifactName: $(ARTIFACT_NAME) +- template: /eng/common/core-templates/steps/generate-sbom.yml + parameters: + is1ESPipeline: false + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/get-delegation-sas.yml b/eng/common/templates/steps/get-delegation-sas.yml index c0e8f91317f..83760c9798e 100644 --- a/eng/common/templates/steps/get-delegation-sas.yml +++ b/eng/common/templates/steps/get-delegation-sas.yml @@ -1,43 +1,7 @@ -parameters: -- name: federatedServiceConnection - type: string -- name: outputVariableName - type: string -- name: expiryInHours - type: number - default: 1 -- name: base64Encode - type: boolean - default: false -- name: storageAccount - type: string -- name: container - type: string -- name: permissions - type: string - default: 'rl' - steps: -- task: AzureCLI@2 - displayName: 'Generate delegation SAS Token for ${{ parameters.storageAccount }}/${{ parameters.container }}' - inputs: - azureSubscription: ${{ parameters.federatedServiceConnection }} - scriptType: 'pscore' - scriptLocation: 'inlineScript' - inlineScript: | - # Calculate the expiration of the SAS token and convert to UTC - $expiry = (Get-Date).AddHours(${{ parameters.expiryInHours }}).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") - - $sas = az storage container generate-sas --account-name ${{ parameters.storageAccount }} --name ${{ parameters.container }} --permissions ${{ parameters.permissions }} --expiry $expiry --auth-mode login --as-user -o tsv - - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to generate SAS token." - exit 1 - } - - if ('${{ parameters.base64Encode }}' -eq 'true') { - $sas = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($sas)) - } +- template: /eng/common/core-templates/steps/get-delegation-sas.yml + parameters: + is1ESPipeline: false - Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true]$sas" + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/get-federated-access-token.yml b/eng/common/templates/steps/get-federated-access-token.yml index d556f9c9fb0..31e151d9d9e 100644 --- a/eng/common/templates/steps/get-federated-access-token.yml +++ b/eng/common/templates/steps/get-federated-access-token.yml @@ -1,40 +1,7 @@ -parameters: -- name: federatedServiceConnection - type: string -- name: outputVariableName - type: string -- name: stepName - type: string - default: 'getFederatedAccessToken' -- name: condition - type: string - default: '' -# Resource to get a token for. Common values include: -# - '499b84ac-1321-427f-aa17-267ca6975798' for Azure DevOps -# - 'https://storage.azure.com/' for storage -# Defaults to Azure DevOps -- name: resource - type: string - default: '499b84ac-1321-427f-aa17-267ca6975798' -- name: isStepOutputVariable - type: boolean - default: false - steps: -- task: AzureCLI@2 - displayName: 'Getting federated access token for feeds' - name: ${{ parameters.stepName }} - ${{ if ne(parameters.condition, '') }}: - condition: ${{ parameters.condition }} - inputs: - azureSubscription: ${{ parameters.federatedServiceConnection }} - scriptType: 'pscore' - scriptLocation: 'inlineScript' - inlineScript: | - $accessToken = az account get-access-token --query accessToken --resource ${{ parameters.resource }} --output tsv - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to get access token for resource '${{ parameters.resource }}'" - exit 1 - } - Write-Host "Setting '${{ parameters.outputVariableName }}' with the access token value" - Write-Host "##vso[task.setvariable variable=${{ parameters.outputVariableName }};issecret=true;isOutput=${{ parameters.isStepOutputVariable }}]$accessToken" +- template: /eng/common/core-templates/steps/get-federated-access-token.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} \ No newline at end of file diff --git a/eng/common/templates/steps/publish-build-artifacts.yml b/eng/common/templates/steps/publish-build-artifacts.yml new file mode 100644 index 00000000000..6428a98dfef --- /dev/null +++ b/eng/common/templates/steps/publish-build-artifacts.yml @@ -0,0 +1,40 @@ +parameters: +- name: is1ESPipeline + type: boolean + default: false + +- name: displayName + type: string + default: 'Publish to Build Artifact' + +- name: condition + type: string + default: succeeded() + +- name: artifactName + type: string + +- name: pathToPublish + type: string + +- name: continueOnError + type: boolean + default: false + +- name: publishLocation + type: string + default: 'Container' + +steps: +- ${{ if eq(parameters.is1ESPipeline, true) }}: + - 'eng/common/templates cannot be referenced from a 1ES managed template': error +- task: PublishBuildArtifacts@1 + displayName: ${{ parameters.displayName }} + condition: ${{ parameters.condition }} + ${{ if parameters.continueOnError }}: + continueOnError: ${{ parameters.continueOnError }} + inputs: + PublishLocation: ${{ parameters.publishLocation }} + PathtoPublish: ${{ parameters.pathToPublish }} + ${{ if parameters.artifactName }}: + ArtifactName: ${{ parameters.artifactName }} \ No newline at end of file diff --git a/eng/common/templates/steps/publish-logs.yml b/eng/common/templates/steps/publish-logs.yml index 88f238f36bf..4ea86bd8823 100644 --- a/eng/common/templates/steps/publish-logs.yml +++ b/eng/common/templates/steps/publish-logs.yml @@ -1,23 +1,7 @@ -parameters: - StageLabel: '' - JobLabel: '' - steps: -- task: Powershell@2 - displayName: Prepare Binlogs to Upload - inputs: - targetType: inline - script: | - New-Item -ItemType Directory $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ - Move-Item -Path $(Build.SourcesDirectory)/artifacts/log/Debug/* $(Build.SourcesDirectory)/PostBuildLogs/${{parameters.StageLabel}}/${{parameters.JobLabel}}/ - continueOnError: true - condition: always() +- template: /eng/common/core-templates/steps/publish-logs.yml + parameters: + is1ESPipeline: false -- task: PublishBuildArtifacts@1 - displayName: Publish Logs - inputs: - PathtoPublish: '$(Build.SourcesDirectory)/PostBuildLogs' - PublishLocation: Container - ArtifactName: PostBuildLogs - continueOnError: true - condition: always() + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/publish-pipeline-artifacts.yml b/eng/common/templates/steps/publish-pipeline-artifacts.yml new file mode 100644 index 00000000000..5dd698b212f --- /dev/null +++ b/eng/common/templates/steps/publish-pipeline-artifacts.yml @@ -0,0 +1,34 @@ +parameters: +- name: is1ESPipeline + type: boolean + default: false + +- name: args + type: object + default: {} + +steps: +- ${{ if eq(parameters.is1ESPipeline, true) }}: + - 'eng/common/templates cannot be referenced from a 1ES managed template': error +- task: PublishPipelineArtifact@1 + displayName: ${{ coalesce(parameters.args.displayName, 'Publish to Build Artifact') }} + ${{ if parameters.args.condition }}: + condition: ${{ parameters.args.condition }} + ${{ else }}: + condition: succeeded() + ${{ if parameters.args.continueOnError }}: + continueOnError: ${{ parameters.args.continueOnError }} + inputs: + targetPath: ${{ parameters.args.targetPath }} + ${{ if parameters.args.artifactName }}: + artifactName: ${{ parameters.args.artifactName }} + ${{ if parameters.args.publishLocation }}: + publishLocation: ${{ parameters.args.publishLocation }} + ${{ if parameters.args.fileSharePath }}: + fileSharePath: ${{ parameters.args.fileSharePath }} + ${{ if parameters.args.Parallel }}: + parallel: ${{ parameters.args.Parallel }} + ${{ if parameters.args.parallelCount }}: + parallelCount: ${{ parameters.args.parallelCount }} + ${{ if parameters.args.properties }}: + properties: ${{ parameters.args.properties }} \ No newline at end of file diff --git a/eng/common/templates/steps/retain-build.yml b/eng/common/templates/steps/retain-build.yml index 83d97a26a01..8e841ace3d2 100644 --- a/eng/common/templates/steps/retain-build.yml +++ b/eng/common/templates/steps/retain-build.yml @@ -1,28 +1,7 @@ -parameters: - # Optional azure devops PAT with build execute permissions for the build's organization, - # only needed if the build that should be retained ran on a different organization than - # the pipeline where this template is executing from - Token: '' - # Optional BuildId to retain, defaults to the current running build - BuildId: '' - # Azure devops Organization URI for the build in the https://dev.azure.com/ format. - # Defaults to the organization the current pipeline is running on - AzdoOrgUri: '$(System.CollectionUri)' - # Azure devops project for the build. Defaults to the project the current pipeline is running on - AzdoProject: '$(System.TeamProject)' - steps: - - task: powershell@2 - inputs: - targetType: 'filePath' - filePath: eng/common/retain-build.ps1 - pwsh: true - arguments: > - -AzdoOrgUri: ${{parameters.AzdoOrgUri}} - -AzdoProject ${{parameters.AzdoProject}} - -Token ${{coalesce(parameters.Token, '$env:SYSTEM_ACCESSTOKEN') }} - -BuildId ${{coalesce(parameters.BuildId, '$env:BUILD_ID')}} - displayName: Enable permanent build retention - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - BUILD_ID: $(Build.BuildId) \ No newline at end of file +- template: /eng/common/core-templates/steps/retain-build.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/run-on-unix.yml b/eng/common/templates/steps/run-on-unix.yml deleted file mode 100644 index e1733814f65..00000000000 --- a/eng/common/templates/steps/run-on-unix.yml +++ /dev/null @@ -1,7 +0,0 @@ -parameters: - agentOs: '' - steps: [] - -steps: -- ${{ if ne(parameters.agentOs, 'Windows_NT') }}: - - ${{ parameters.steps }} diff --git a/eng/common/templates/steps/run-on-windows.yml b/eng/common/templates/steps/run-on-windows.yml deleted file mode 100644 index 73e7e9c275a..00000000000 --- a/eng/common/templates/steps/run-on-windows.yml +++ /dev/null @@ -1,7 +0,0 @@ -parameters: - agentOs: '' - steps: [] - -steps: -- ${{ if eq(parameters.agentOs, 'Windows_NT') }}: - - ${{ parameters.steps }} diff --git a/eng/common/templates/steps/run-script-ifequalelse.yml b/eng/common/templates/steps/run-script-ifequalelse.yml deleted file mode 100644 index 3d1242f5587..00000000000 --- a/eng/common/templates/steps/run-script-ifequalelse.yml +++ /dev/null @@ -1,33 +0,0 @@ -parameters: - # if parameter1 equals parameter 2, run 'ifScript' command, else run 'elsescript' command - parameter1: '' - parameter2: '' - ifScript: '' - elseScript: '' - - # name of script step - name: Script - - # display name of script step - displayName: If-Equal-Else Script - - # environment - env: {} - - # conditional expression for step execution - condition: '' - -steps: -- ${{ if and(ne(parameters.ifScript, ''), eq(parameters.parameter1, parameters.parameter2)) }}: - - script: ${{ parameters.ifScript }} - name: ${{ parameters.name }} - displayName: ${{ parameters.displayName }} - env: ${{ parameters.env }} - condition: ${{ parameters.condition }} - -- ${{ if and(ne(parameters.elseScript, ''), ne(parameters.parameter1, parameters.parameter2)) }}: - - script: ${{ parameters.elseScript }} - name: ${{ parameters.name }} - displayName: ${{ parameters.displayName }} - env: ${{ parameters.env }} - condition: ${{ parameters.condition }} \ No newline at end of file diff --git a/eng/common/templates/steps/send-to-helix.yml b/eng/common/templates/steps/send-to-helix.yml index 3eb7e2d5f84..39f99fc2762 100644 --- a/eng/common/templates/steps/send-to-helix.yml +++ b/eng/common/templates/steps/send-to-helix.yml @@ -1,91 +1,7 @@ -# Please remember to update the documentation if you make changes to these parameters! -parameters: - HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ - HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' - HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number - HelixTargetQueues: '' # required -- semicolon-delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues - HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group - HelixConfiguration: '' # optional -- additional property attached to a job - HelixPreCommands: '' # optional -- commands to run before Helix work item execution - HelixPostCommands: '' # optional -- commands to run after Helix work item execution - WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects - WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects - WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects - CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload - XUnitProjects: '' # optional -- semicolon-delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true - XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects - XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects - XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner - XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects - IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion - DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json - DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json - WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." - IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set - HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting https://helix.int-dot.net ) - Creator: '' # optional -- if the build is external, use this to specify who is sending the job - DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO - condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() - continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false - steps: - - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' - displayName: ${{ parameters.DisplayNamePrefix }} (Windows) - env: - BuildConfig: $(_BuildConfig) - HelixSource: ${{ parameters.HelixSource }} - HelixType: ${{ parameters.HelixType }} - HelixBuild: ${{ parameters.HelixBuild }} - HelixConfiguration: ${{ parameters.HelixConfiguration }} - HelixTargetQueues: ${{ parameters.HelixTargetQueues }} - HelixAccessToken: ${{ parameters.HelixAccessToken }} - HelixPreCommands: ${{ parameters.HelixPreCommands }} - HelixPostCommands: ${{ parameters.HelixPostCommands }} - WorkItemDirectory: ${{ parameters.WorkItemDirectory }} - WorkItemCommand: ${{ parameters.WorkItemCommand }} - WorkItemTimeout: ${{ parameters.WorkItemTimeout }} - CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} - XUnitProjects: ${{ parameters.XUnitProjects }} - XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} - XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} - XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} - XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} - IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} - DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} - DotNetCliVersion: ${{ parameters.DotNetCliVersion }} - WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} - HelixBaseUri: ${{ parameters.HelixBaseUri }} - Creator: ${{ parameters.Creator }} - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} - - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /p:TreatWarningsAsErrors=false /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog - displayName: ${{ parameters.DisplayNamePrefix }} (Unix) - env: - BuildConfig: $(_BuildConfig) - HelixSource: ${{ parameters.HelixSource }} - HelixType: ${{ parameters.HelixType }} - HelixBuild: ${{ parameters.HelixBuild }} - HelixConfiguration: ${{ parameters.HelixConfiguration }} - HelixTargetQueues: ${{ parameters.HelixTargetQueues }} - HelixAccessToken: ${{ parameters.HelixAccessToken }} - HelixPreCommands: ${{ parameters.HelixPreCommands }} - HelixPostCommands: ${{ parameters.HelixPostCommands }} - WorkItemDirectory: ${{ parameters.WorkItemDirectory }} - WorkItemCommand: ${{ parameters.WorkItemCommand }} - WorkItemTimeout: ${{ parameters.WorkItemTimeout }} - CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} - XUnitProjects: ${{ parameters.XUnitProjects }} - XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} - XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} - XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} - XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} - IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} - DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} - DotNetCliVersion: ${{ parameters.DotNetCliVersion }} - WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} - HelixBaseUri: ${{ parameters.HelixBaseUri }} - Creator: ${{ parameters.Creator }} - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} +- template: /eng/common/core-templates/steps/send-to-helix.yml + parameters: + is1ESPipeline: false + + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/source-build.yml b/eng/common/templates/steps/source-build.yml index 41bbb915736..23c1d6f4e9f 100644 --- a/eng/common/templates/steps/source-build.yml +++ b/eng/common/templates/steps/source-build.yml @@ -1,129 +1,7 @@ -parameters: - # This template adds arcade-powered source-build to CI. - - # This is a 'steps' template, and is intended for advanced scenarios where the existing build - # infra has a careful build methodology that must be followed. For example, a repo - # (dotnet/runtime) might choose to clone the GitHub repo only once and store it as a pipeline - # artifact for all subsequent jobs to use, to reduce dependence on a strong network connection to - # GitHub. Using this steps template leaves room for that infra to be included. - - # Defines the platform on which to run the steps. See 'eng/common/templates/job/source-build.yml' - # for details. The entire object is described in the 'job' template for simplicity, even though - # the usage of the properties on this object is split between the 'job' and 'steps' templates. - platform: {} - steps: -# Build. Keep it self-contained for simple reusability. (No source-build-specific job variables.) -- script: | - set -x - df -h - - # If building on the internal project, the artifact feeds variable may be available (usually only if needed) - # In that case, call the feed setup script to add internal feeds corresponding to public ones. - # In addition, add an msbuild argument to copy the WIP from the repo to the target build location. - # This is because SetupNuGetSources.sh will alter the current NuGet.config file, and we need to preserve those - # changes. - internalRestoreArgs= - if [ '$(dn-bot-dnceng-artifact-feeds-rw)' != '$''(dn-bot-dnceng-artifact-feeds-rw)' ]; then - # Temporarily work around https://github.com/dotnet/arcade/issues/7709 - chmod +x $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh - $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh $(Build.SourcesDirectory)/NuGet.config $(dn-bot-dnceng-artifact-feeds-rw) - internalRestoreArgs='/p:CopyWipIntoInnerSourceBuildRepo=true' - - # The 'Copy WIP' feature of source build uses git stash to apply changes from the original repo. - # This only works if there is a username/email configured, which won't be the case in most CI runs. - git config --get user.email - if [ $? -ne 0 ]; then - git config user.email dn-bot@microsoft.com - git config user.name dn-bot - fi - fi - - # If building on the internal project, the internal storage variable may be available (usually only if needed) - # In that case, add variables to allow the download of internal runtimes if the specified versions are not found - # in the default public locations. - internalRuntimeDownloadArgs= - if [ '$(dotnetbuilds-internal-container-read-token-base64)' != '$''(dotnetbuilds-internal-container-read-token-base64)' ]; then - internalRuntimeDownloadArgs='/p:DotNetRuntimeSourceFeed=https://dotnetbuilds.blob.core.windows.net/internal /p:DotNetRuntimeSourceFeedKey=$(dotnetbuilds-internal-container-read-token-base64) --runtimesourcefeed https://dotnetbuilds.blob.core.windows.net/internal --runtimesourcefeedkey $(dotnetbuilds-internal-container-read-token-base64)' - fi - - buildConfig=Release - # Check if AzDO substitutes in a build config from a variable, and use it if so. - if [ '$(_BuildConfig)' != '$''(_BuildConfig)' ]; then - buildConfig='$(_BuildConfig)' - fi - - officialBuildArgs= - if [ '${{ and(ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}' = 'True' ]; then - officialBuildArgs='/p:DotNetPublishUsingPipelines=true /p:OfficialBuildId=$(BUILD.BUILDNUMBER)' - fi - - targetRidArgs= - if [ '${{ parameters.platform.targetRID }}' != '' ]; then - targetRidArgs='/p:TargetRid=${{ parameters.platform.targetRID }}' - fi - - runtimeOsArgs= - if [ '${{ parameters.platform.runtimeOS }}' != '' ]; then - runtimeOsArgs='/p:RuntimeOS=${{ parameters.platform.runtimeOS }}' - fi - - baseOsArgs= - if [ '${{ parameters.platform.baseOS }}' != '' ]; then - baseOsArgs='/p:BaseOS=${{ parameters.platform.baseOS }}' - fi - - publishArgs= - if [ '${{ parameters.platform.skipPublishValidation }}' != 'true' ]; then - publishArgs='--publish' - fi - - assetManifestFileName=SourceBuild_RidSpecific.xml - if [ '${{ parameters.platform.name }}' != '' ]; then - assetManifestFileName=SourceBuild_${{ parameters.platform.name }}.xml - fi - - ${{ coalesce(parameters.platform.buildScript, './build.sh') }} --ci \ - --configuration $buildConfig \ - --restore --build --pack $publishArgs -bl \ - $officialBuildArgs \ - $internalRuntimeDownloadArgs \ - $internalRestoreArgs \ - $targetRidArgs \ - $runtimeOsArgs \ - $baseOsArgs \ - /p:SourceBuildNonPortable=${{ parameters.platform.nonPortable }} \ - /p:ArcadeBuildFromSource=true \ - /p:AssetManifestFileName=$assetManifestFileName - displayName: Build - -# Upload build logs for diagnosis. -- task: CopyFiles@2 - displayName: Prepare BuildLogs staging directory - inputs: - SourceFolder: '$(Build.SourcesDirectory)' - Contents: | - **/*.log - **/*.binlog - artifacts/source-build/self/prebuilt-report/** - TargetFolder: '$(Build.StagingDirectory)/BuildLogs' - CleanTargetFolder: true - continueOnError: true - condition: succeededOrFailed() - -- task: PublishPipelineArtifact@1 - displayName: Publish BuildLogs - inputs: - targetPath: '$(Build.StagingDirectory)/BuildLogs' - artifactName: BuildLogs_SourceBuild_${{ parameters.platform.name }}_Attempt$(System.JobAttempt) - continueOnError: true - condition: succeededOrFailed() +- template: /eng/common/core-templates/steps/source-build.yml + parameters: + is1ESPipeline: false -# Manually inject component detection so that we can ignore the source build upstream cache, which contains -# a nupkg cache of input packages (a local feed). -# This path must match the upstream cache path in property 'CurrentRepoSourceBuiltNupkgCacheDir' -# in src\Microsoft.DotNet.Arcade.Sdk\tools\SourceBuild\SourceBuildArcade.targets -- task: ComponentGovernanceComponentDetection@0 - displayName: Component Detection (Exclude upstream cache) - inputs: - ignoreDirectories: '$(Build.SourcesDirectory)/artifacts/source-build/self/src/artifacts/obj/source-built-upstream-cache' + ${{ each parameter in parameters }}: + ${{ parameter.key }}: ${{ parameter.value }} diff --git a/eng/common/templates/steps/telemetry-end.yml b/eng/common/templates/steps/telemetry-end.yml deleted file mode 100644 index fadc04ca1b9..00000000000 --- a/eng/common/templates/steps/telemetry-end.yml +++ /dev/null @@ -1,102 +0,0 @@ -parameters: - maxRetries: 5 - retryDelay: 10 # in seconds - -steps: -- bash: | - if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then - errorCount=0 - else - errorCount=1 - fi - warningCount=0 - - curlStatus=1 - retryCount=0 - # retry loop to harden against spotty telemetry connections - # we don't retry successes and 4xx client errors - until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] - do - if [ $retryCount -gt 0 ]; then - echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." - sleep $RetryDelay - fi - - # create a temporary file for curl output - res=`mktemp` - - curlResult=` - curl --verbose --output $res --write-out "%{http_code}"\ - -H 'Content-Type: application/json' \ - -H "X-Helix-Job-Token: $Helix_JobToken" \ - -H 'Content-Length: 0' \ - -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \ - --data-urlencode "errorCount=$errorCount" \ - --data-urlencode "warningCount=$warningCount"` - curlStatus=$? - - if [ $curlStatus -eq 0 ]; then - if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then - curlStatus=$curlResult - fi - fi - - let retryCount++ - done - - if [ $curlStatus -ne 0 ]; then - echo "Failed to Send Build Finish information after $retryCount retries" - vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus" - echo "##$vstsLogOutput" - exit 1 - fi - displayName: Send Unix Build End Telemetry - env: - # defined via VSTS variables in start-job.sh - Helix_JobToken: $(Helix_JobToken) - Helix_WorkItemId: $(Helix_WorkItemId) - MaxRetries: ${{ parameters.maxRetries }} - RetryDelay: ${{ parameters.retryDelay }} - condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) -- powershell: | - if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) { - $ErrorCount = 0 - } else { - $ErrorCount = 1 - } - $WarningCount = 0 - - # Basic retry loop to harden against server flakiness - $retryCount = 0 - while ($retryCount -lt $env:MaxRetries) { - try { - Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" ` - -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } - break - } - catch { - $statusCode = $_.Exception.Response.StatusCode.value__ - if ($statusCode -ge 400 -and $statusCode -le 499) { - Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" - Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message - exit 1 - } - Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." - $retryCount++ - sleep $env:RetryDelay - continue - } - } - - if ($retryCount -ge $env:MaxRetries) { - Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." - exit 1 - } - displayName: Send Windows Build End Telemetry - env: - # defined via VSTS variables in start-job.ps1 - Helix_JobToken: $(Helix_JobToken) - Helix_WorkItemId: $(Helix_WorkItemId) - MaxRetries: ${{ parameters.maxRetries }} - RetryDelay: ${{ parameters.retryDelay }} - condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT')) diff --git a/eng/common/templates/steps/telemetry-start.yml b/eng/common/templates/steps/telemetry-start.yml deleted file mode 100644 index 32c01ef0b55..00000000000 --- a/eng/common/templates/steps/telemetry-start.yml +++ /dev/null @@ -1,241 +0,0 @@ -parameters: - helixSource: 'undefined_defaulted_in_telemetry.yml' - helixType: 'undefined_defaulted_in_telemetry.yml' - buildConfig: '' - runAsPublic: false - maxRetries: 5 - retryDelay: 10 # in seconds - -steps: -- ${{ if and(eq(parameters.runAsPublic, 'false'), not(eq(variables['System.TeamProject'], 'public'))) }}: - - task: AzureKeyVault@1 - inputs: - azureSubscription: 'HelixProd_KeyVault' - KeyVaultName: HelixProdKV - SecretsFilter: 'HelixApiAccessToken' - condition: always() -- bash: | - # create a temporary file - jobInfo=`mktemp` - - # write job info content to temporary file - cat > $jobInfo < /dev/null; then echo "Curl failed; dumping some information about dotnet.microsoft.com for later investigation" - echo | openssl s_client -showcerts -servername dotnet.microsoft.com -connect dotnet.microsoft.com:443 + echo | openssl s_client -showcerts -servername dotnet.microsoft.com -connect dotnet.microsoft.com:443 || true fi echo "Will now retry the same URL with verbose logging." with_retries curl "$install_script_url" -sSL --verbose --retry 10 --create-dirs -o "$install_script" || { @@ -343,20 +341,20 @@ function InitializeBuildTool { _InitializeBuildToolCommand="msbuild" # use override if it exists - commonly set by source-build if [[ "${_OverrideArcadeInitializeBuildToolFramework:-x}" == "x" ]]; then - _InitializeBuildToolFramework="net8.0" + _InitializeBuildToolFramework="net9.0" else _InitializeBuildToolFramework="${_OverrideArcadeInitializeBuildToolFramework}" fi } -# Set RestoreNoCache as a workaround for https://github.com/NuGet/Home/issues/3116 +# Set RestoreNoHttpCache as a workaround for https://github.com/NuGet/Home/issues/3116 function GetNuGetPackageCachePath { if [[ -z ${NUGET_PACKAGES:-} ]]; then if [[ "$use_global_nuget_cache" == true ]]; then - export NUGET_PACKAGES="$HOME/.nuget/packages" + export NUGET_PACKAGES="$HOME/.nuget/packages/" else - export NUGET_PACKAGES="$repo_root/.packages" - export RESTORENOCACHE=true + export NUGET_PACKAGES="$repo_root/.packages/" + export RESTORENOHTTPCACHE=true fi fi @@ -440,7 +438,7 @@ function StopProcesses { } function MSBuild { - local args=$@ + local args=( "$@" ) if [[ "$pipelines_log" == true ]]; then InitializeBuildTool InitializeToolset @@ -458,12 +456,10 @@ function MSBuild { local possiblePaths=() possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/$_InitializeBuildToolFramework/Microsoft.DotNet.Arcade.Sdk.dll" ) - possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/netcoreapp2.1/Microsoft.DotNet.Arcade.Sdk.dll" ) - possiblePaths+=( "$toolset_dir/netcoreapp3.1/Microsoft.DotNet.ArcadeLogging.dll" ) - possiblePaths+=( "$toolset_dir/netcoreapp3.1/Microsoft.DotNet.Arcade.Sdk.dll" ) possiblePaths+=( "$toolset_dir/net7.0/Microsoft.DotNet.ArcadeLogging.dll" ) possiblePaths+=( "$toolset_dir/net7.0/Microsoft.DotNet.Arcade.Sdk.dll" ) + possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.ArcadeLogging.dll" ) + possiblePaths+=( "$toolset_dir/net8.0/Microsoft.DotNet.Arcade.Sdk.dll" ) for path in "${possiblePaths[@]}"; do if [[ -f $path ]]; then selectedPath=$path @@ -477,7 +473,7 @@ function MSBuild { args+=( "-logger:$selectedPath" ) fi - MSBuild-Core ${args[@]} + MSBuild-Core "${args[@]}" } function MSBuild-Core { @@ -510,7 +506,8 @@ function MSBuild-Core { echo "Build failed with exit code $exit_code. Check errors above." # When running on Azure Pipelines, override the returned exit code to avoid double logging. - if [[ "$ci" == "true" && -n ${SYSTEM_TEAMPROJECT:-} ]]; then + # Skip this when the build is a child of the VMR orchestrator build. + if [[ "$ci" == true && -n ${SYSTEM_TEAMPROJECT:-} && "$product_build" != true && "$properties" != *"DotNetBuildRepo=true"* ]]; then Write-PipelineSetResult -result "Failed" -message "msbuild execution failed." # Exiting with an exit code causes the azure pipelines task to log yet another "noise" error # The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error diff --git a/eng/dependabot/Packages.props b/eng/dependabot/Packages.props deleted file mode 100644 index 921ae22ea46..00000000000 --- a/eng/dependabot/Packages.props +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/eng/dependabot/dependabot.csproj b/eng/dependabot/dependabot.csproj deleted file mode 100644 index b760d21b0e8..00000000000 --- a/eng/dependabot/dependabot.csproj +++ /dev/null @@ -1,4 +0,0 @@ - - \ No newline at end of file diff --git a/exclusion.dic b/exclusion.dic new file mode 100644 index 00000000000..554b46b3423 --- /dev/null +++ b/exclusion.dic @@ -0,0 +1,69 @@ +semver +infos +nupkg +nuget +langpacks +templateengine +constantine +noops +balancednesting +expandvariables +dotnetcli +sdks +maui +nuspec +mytemplate +myoption +myname +othername +templatecache +firstrun +netcoreapp +netstandard +doesn +installe +templatestrings +firefox +sasl +lockd +amanda +ndbpx +msbuild +haml +jsonld +hjson +geojson +topojson +bowerrc +npmrc +postcssrc +babelrc +csslintrc +eslintrc +lintrc +jshintrc +stylelintrc +yarnrc +cshtml +vbhtml +proj +pubxml +aspx +vsixmanifest +vsct +axml +plist +resx +axaml +yaml +dockerfile +gitattributes +dockerignore +gitignore +locs +globbing +filelist +deserializer +awaiter +nupkgs +parsable diff --git a/github-merge-flow.jsonc b/github-merge-flow.jsonc new file mode 100644 index 00000000000..44255824ce6 --- /dev/null +++ b/github-merge-flow.jsonc @@ -0,0 +1,20 @@ +// IMPORTANT: This file is read by the merge flow from main branch only. +{ + "merge-flow-configurations": { + // Automate opening PRs to merge cli release/8.0.1xx to 8.0.3xx + "release/8.0.1xx":{ + "MergeToBranch": "release/8.0.3xx", + "ExtraSwitches": "-QuietComments" + }, + // Automate opening PRs to merge cli release/8.0.3xx to 8.0.4xx + "release/8.0.3xx":{ + "MergeToBranch": "release/8.0.4xx", + "ExtraSwitches": "-QuietComments" + }, + // Automate opening PRs to merge sdk repos from release/8.0.4xx to main + "release/8.0.4xx":{ + "MergeToBranch": "main", + "ExtraSwitches": "-QuietComments" + } + } +} diff --git a/global.json b/global.json index b80ec640130..afa69f0e70a 100644 --- a/global.json +++ b/global.json @@ -1,8 +1,8 @@ { "tools": { - "dotnet": "8.0.107" + "dotnet": "9.0.100-preview.5.24307.3" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.24376.1" + "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.24408.2" } } diff --git a/search-cache-pipeline.yml b/search-cache-pipeline.yml index c973ce8f574..12ca7e9f482 100644 --- a/search-cache-pipeline.yml +++ b/search-cache-pipeline.yml @@ -1,3 +1,6 @@ +# templating-search-cache-updater +# https://dev.azure.com/dnceng/internal/_build?definitionId=1025 + # Don't trigger for CI events: push, PR created etc. trigger: none # Trigger periodically instead. @@ -15,160 +18,151 @@ parameters: type: boolean default: true -pool: - name: NetCore1ESPool-Internal - demands: ImageOverride -equals Build.Ubuntu.2004.Amd64 - -steps: -- checkout: self - -- script: '$(Build.SourcesDirectory)/build.sh' - -- task: CopyFiles@2 - displayName: Gather Test Log and Results - inputs: - SourceFolder: '$(Build.SourcesDirectory)/artifacts' - Contents: | - log/**/* - TestResults/**/* - TargetFolder: '$(Build.ArtifactStagingDirectory)' - continueOnError: true - condition: always() - -- task: PublishBuildArtifacts@1 - displayName: Publish Test Log and Results - inputs: - PathtoPublish: '$(Build.ArtifactStagingDirectory)' - ArtifactName: Test_LogResults - publishLocation: Container - continueOnError: true - condition: always() - -- task: UseDotNet@2 - displayName: 'Use .NET 3.1' - inputs: - packageType: sdk - version: 3.1.x - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 5.0.100' - inputs: - packageType: sdk - version: 5.0.100 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 5.0.400' - inputs: - packageType: sdk - version: 5.0.400 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 6.0.100' - inputs: - packageType: sdk - version: 6.0.100 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 6.0.300' - inputs: - packageType: sdk - version: 6.0.300 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 6.0.400' - inputs: - packageType: sdk - version: 6.0.400 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 7.0.100' - inputs: - packageType: sdk - version: 7.0.100 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- task: UseDotNet@2 - displayName: 'Use .NET 7.0.200' - inputs: - packageType: sdk - version: 7.0.200 - installationPath: $(Build.SourcesDirectory)/.dotnet - -- bash: > - curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin - -Channel 7.0.3xx - -Quality daily - -InstallDir $(Build.SourcesDirectory)/.dotnet - -SkipNonVersionedFiles - displayName: Install daily .NET 7.0.3xx - -- bash: > - curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin - -Channel 8.0.1xx - -Quality daily - -InstallDir $(Build.SourcesDirectory)/.dotnet - -SkipNonVersionedFiles - displayName: Install latest daily .NET version - -- bash: > - $(Build.SourcesDirectory)/.dotnet/dotnet $(Build.SourcesDirectory)/artifacts/bin/Microsoft.TemplateSearch.TemplateDiscovery/Debug/net8.0/Microsoft.TemplateSearch.TemplateDiscovery.dll - --basePath $(System.DefaultWorkingDirectory)/NugetDownloadDirectory --allowPreviewPacks -v --test --diff $(EnableDiffMode) - displayName: Run Cache Updater - -- task: CopyFiles@2 - inputs: - SourceFolder: $(System.DefaultWorkingDirectory)/NugetDownloadDirectory/SearchCache/ - Contents: | - NuGetTemplateSearchInfo*.json - nonTemplatePacks.json - TargetFolder: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/ - -- publish: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/ - artifact: outputs - displayName: Publish Artifacts - -- ${{ if eq(parameters.publishToBlob, true) }}: - - script: '$(Build.SourcesDirectory)/eng/SearchCache/InstallAzureCLI.sh' - displayName: Install Azure CLI - - - bash: az config set extension.use_dynamic_install=yes_without_prompt - displayName: Disable Azure CLI prompts - - - bash: > - az storage azcopy blob upload - -c $(CacheFileStorageContainer) - --account-name $(CacheFileStorageAccount) - -s '$(System.DefaultWorkingDirectory)/ArtifactsToPublish/NuGetTemplateSearchInfoVer2.json' - --sas-token "$(CacheFileStorageSasToken)" - -d NuGetTemplateSearchInfoVer2.json - | tee upload.log - && grep ".*Number of Transfers Completed: 1" upload.log || (echo ; echo "Cache file upload failed"; false) - displayName: Upload to blob storage - - - bash: > - az storage azcopy blob upload - -c $(LegacyCacheFileStorageContainer) - --account-name $(LegacyCacheFileStorageAccount) - -s '$(System.DefaultWorkingDirectory)/ArtifactsToPublish/NuGetTemplateSearchInfo.json' - --sas-token "$(LegacyCacheFileStorageSasToken)" - -d NuGetTemplateSearchInfo.json - | tee upload-legacy.log - && grep ".*Number of Transfers Completed: 1" upload-legacy.log || (echo ; echo "Legacy cache file upload failed"; false) - displayName: Upload legacy file to blob storage - - - bash: > - az storage azcopy blob upload - -c $(NonTemplatePacksFileStorageContainer) - --account-name $(NonTemplatePacksFileStorageAccount) - -s '$(System.DefaultWorkingDirectory)/ArtifactsToPublish/nonTemplatePacks.json' - --sas-token "$(NonTemplatePacksFileStorageSasToken)" - -d nonTemplatePacks.json - | tee upload-non-template-packs.log - && grep ".*Number of Transfers Completed: 1" upload-non-template-packs.log || (echo ; echo "Legacy cache file upload failed"; false) - displayName: Upload non template packages file to blob storage +variables: +# Variables used: DncEngInternalBuildPool +- template: /eng/common/templates-official/variables/pool-providers.yml + +resources: + repositories: + - repository: 1ESPipelineTemplates + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release + +extends: + template: v1/1ES.Official.PipelineTemplate.yml@1ESPipelineTemplates + parameters: + sdl: + sourceAnalysisPool: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + stages: + - stage: Build + jobs: + - job: Create + pool: + name: $(DncEngInternalBuildPool) + image: 1es-ubuntu-2204 + os: linux + templateContext: + outputs: + - output: pipelineArtifact + targetPath: $(Build.ArtifactStagingDirectory) + artifactName: Test_LogResults + - output: pipelineArtifact + targetPath: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/ + artifactName: ArtifactsToPublish + + steps: + - script: $(Build.SourcesDirectory)/build.sh + displayName: Build + + - task: CopyFiles@2 + displayName: Gather Test Log and Results + inputs: + SourceFolder: $(Build.SourcesDirectory)/artifacts + Contents: | + log/**/* + TestResults/**/* + TargetFolder: $(Build.ArtifactStagingDirectory) + continueOnError: true + condition: always() + + - task: UseDotNet@2 + displayName: Use .NET 6.0.100 + inputs: + packageType: sdk + version: 6.0.100 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - task: UseDotNet@2 + displayName: Use .NET 6.0.300 + inputs: + packageType: sdk + version: 6.0.300 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - task: UseDotNet@2 + displayName: Use .NET 6.0.400 + inputs: + packageType: sdk + version: 6.0.400 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - task: UseDotNet@2 + displayName: Use .NET 7.0.100 + inputs: + packageType: sdk + version: 7.0.100 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - task: UseDotNet@2 + displayName: Use .NET 7.0.200 + inputs: + packageType: sdk + version: 7.0.200 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - task: UseDotNet@2 + displayName: Use .NET 8.0.200 + inputs: + packageType: sdk + version: 8.0.200 + installationPath: $(Build.SourcesDirectory)/.dotnet + + - bash: > + curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin + -Channel 7.0.3xx + -Quality daily + -InstallDir $(Build.SourcesDirectory)/.dotnet + -SkipNonVersionedFiles + displayName: Install daily .NET 7.0.3xx + + - bash: > + curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin + -Channel 8.0.1xx + -Quality daily + -InstallDir $(Build.SourcesDirectory)/.dotnet + -SkipNonVersionedFiles + displayName: Install latest daily .NET version + + - bash: > + $(Build.SourcesDirectory)/.dotnet/dotnet $(Build.SourcesDirectory)/artifacts/bin/Microsoft.TemplateSearch.TemplateDiscovery/Debug/net9.0/Microsoft.TemplateSearch.TemplateDiscovery.dll --basePath $(System.DefaultWorkingDirectory)/NugetDownloadDirectory --allowPreviewPacks -v --test --diff $(EnableDiffMode) + displayName: Run Cache Updater + + - task: CopyFiles@2 + displayName: Copy artifacts to publish + inputs: + SourceFolder: $(System.DefaultWorkingDirectory)/NugetDownloadDirectory/SearchCache/ + Contents: | + NuGetTemplateSearchInfo*.json + nonTemplatePacks.json + TargetFolder: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/ + + - ${{ if eq(parameters.publishToBlob, true) }}: + # An entirely separate job is required to run AzureFileCopy@6, which is a Windows-only task. + # If the Create job was rewritten to use PowerShell instead of Bash, Create and Publish could be combined into a single Windows job. + - job: Publish + dependsOn: Create + pool: + name: $(DncEngInternalBuildPool) + image: 1es-windows-2022 + os: windows + templateContext: + inputs: + - input: pipelineArtifact + targetPath: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/ + artifactName: ArtifactsToPublish + + steps: + - task: AzureFileCopy@6 + displayName: Upload to blob storage + inputs: + SourcePath: $(System.DefaultWorkingDirectory)/ArtifactsToPublish/*.json + # Service connection: https://dnceng.visualstudio.com/internal/_settings/adminservices?resourceId=010b0bdc-9487-484f-af2d-ca3ae3235b84 + azureSubscription: DOTNET-Templating - PME + Destination: AzureBlob + # These variables are defined in the pipeline's Variables UI. + storage: $(CacheFileStorageAccount) + ContainerName: $(CacheFileStorageContainer) \ No newline at end of file diff --git a/src/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs b/src/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs index 7f47292f9e5..faacc3ef1da 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Abstractions.Components { /// @@ -18,7 +15,7 @@ public interface IBindSymbolSource : IPrioritizedComponent public string DisplayName { get; } /// - /// Prefix that is used in binding to refernece the component. + /// Prefix that is used in binding to reference the component. /// public string? SourcePrefix { get; } @@ -28,12 +25,12 @@ public interface IBindSymbolSource : IPrioritizedComponent public bool RequiresPrefixMatch { get; } /// - /// Gets the value corresponding to . + /// Gets the value corresponding to . /// /// template engine environment settings. - /// the value to retrieve (without prefix). + /// the value to retrieve (without prefix). /// cancellation token. /// - public Task GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindname, CancellationToken cancellationToken); + public Task GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindName, CancellationToken cancellationToken); } } diff --git a/src/Microsoft.TemplateEngine.Abstractions/Components/ISdkInfoProvider.cs b/src/Microsoft.TemplateEngine.Abstractions/Components/ISdkInfoProvider.cs index 65c33a0536c..7074e49488b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Components/ISdkInfoProvider.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Components/ISdkInfoProvider.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Abstractions.Components { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Components/IWorkloadsInfoProvider.cs b/src/Microsoft.TemplateEngine.Abstractions/Components/IWorkloadsInfoProvider.cs index a582e8872f4..8aeb8ae4317 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Components/IWorkloadsInfoProvider.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Components/IWorkloadsInfoProvider.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Abstractions.Components { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraintFactory.cs b/src/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraintFactory.cs index 01104506a73..3cd676c43e6 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraintFactory.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraintFactory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Abstractions.Constraints { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintInfo.cs index 1e6d23ca9d0..9b14c7aab84 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintInfo.cs @@ -1,17 +1,15 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.Constraints { /// - /// Represents information about template constraint defintion in template cache . + /// Represents information about template constraint definition in template cache . /// public class TemplateConstraintInfo { /// - /// Creates instance of the clase. + /// Creates a new instance of . /// /// Constraint type, matches the type defined in implementation and template.json. /// Arguments for constraint evaluation. @@ -33,7 +31,7 @@ public TemplateConstraintInfo(string type, string? args) public string Type { get; } /// - /// Gets the constraint argumens. + /// Gets the constraint arguments. /// public string? Args { get; } } diff --git a/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintResult.cs b/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintResult.cs index aa4d275005b..162cde0502f 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintResult.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Constraints/TemplateConstraintResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.Constraints { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IAllowDefaultIfOptionWithoutValue.cs b/src/Microsoft.TemplateEngine.Abstractions/IAllowDefaultIfOptionWithoutValue.cs index 0f6d58f227c..976903cf8d0 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IAllowDefaultIfOptionWithoutValue.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IAllowDefaultIfOptionWithoutValue.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { [Obsolete("Use DefaultIfOptionWithoutValue property of ITemplateParameter interface instead.")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/IBaselineInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/IBaselineInfo.cs index 6d1e7e387b2..f54563163d3 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IBaselineInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IBaselineInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ICacheParameter.cs b/src/Microsoft.TemplateEngine.Abstractions/ICacheParameter.cs index 859d6b46c5b..d0c3862b7a6 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ICacheParameter.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ICacheParameter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ICacheTag.cs b/src/Microsoft.TemplateEngine.Abstractions/ICacheTag.cs index 70877ae9831..9354d92b4da 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ICacheTag.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ICacheTag.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs b/src/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs index 6ef6ea38d0b..acb80ed6e33 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ICreationEffects.cs b/src/Microsoft.TemplateEngine.Abstractions/ICreationEffects.cs index 8a2563e9244..f50054f5526 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ICreationEffects.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ICreationEffects.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ICreationResult.cs b/src/Microsoft.TemplateEngine.Abstractions/ICreationResult.cs index 9266d1c8b19..206644a39dc 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ICreationResult.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ICreationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs b/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs index 5cd45abf5fd..a3a657b4982 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IEnvironment.cs b/src/Microsoft.TemplateEngine.Abstractions/IEnvironment.cs index 2c6ff00123f..4769b8025bb 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IEnvironment.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IEnvironment.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IFileChange.cs b/src/Microsoft.TemplateEngine.Abstractions/IFileChange.cs index 4754f22d2cd..2dd0b951703 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IFileChange.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IFileChange.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IGenerator.cs b/src/Microsoft.TemplateEngine.Abstractions/IGenerator.cs index 0856b584044..b31ac5cc929 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IGenerator.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IGenerator.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Abstractions.Parameters; diff --git a/src/Microsoft.TemplateEngine.Abstractions/IIdentifiedComponent.cs b/src/Microsoft.TemplateEngine.Abstractions/IIdentifiedComponent.cs index 2761d90f469..8bd896e27e4 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IIdentifiedComponent.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IIdentifiedComponent.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ILocalizationLocator.cs b/src/Microsoft.TemplateEngine.Abstractions/ILocalizationLocator.cs index d265e3294ee..defe2d8aa32 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ILocalizationLocator.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ILocalizationLocator.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IParameterSet.cs b/src/Microsoft.TemplateEngine.Abstractions/IParameterSet.cs index 6128eb60e45..590cfddc717 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IParameterSet.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IParameterSet.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IParameterSymbolLocalizationModel.cs b/src/Microsoft.TemplateEngine.Abstractions/IParameterSymbolLocalizationModel.cs index 4ef188fa594..f67a572e44e 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IParameterSymbolLocalizationModel.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IParameterSymbolLocalizationModel.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IPostAction.cs b/src/Microsoft.TemplateEngine.Abstractions/IPostAction.cs index df70f738b1e..31c78d38102 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IPostAction.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IPostAction.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IScanTemplateInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/IScanTemplateInfo.cs index b53fc120446..2c1517e6f0b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IScanTemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IScanTemplateInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ISearchPackFilter.cs b/src/Microsoft.TemplateEngine.Abstractions/ISearchPackFilter.cs index a361bd45804..e29c1e3e9f2 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ISearchPackFilter.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ISearchPackFilter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { [Obsolete("The interface is moved to Microsoft.TemplateSearch.Common.")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/ISettingsLoader.cs b/src/Microsoft.TemplateEngine.Abstractions/ISettingsLoader.cs index 98460a8a864..8bed6fe3d5b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ISettingsLoader.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ISettingsLoader.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Abstractions diff --git a/src/Microsoft.TemplateEngine.Abstractions/IShortNameList.cs b/src/Microsoft.TemplateEngine.Abstractions/IShortNameList.cs index 9a79626b73e..f3e24ddc07b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IShortNameList.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IShortNameList.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { [Obsolete("The ShortNameList is added to ITemplateInfo instead")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/ISimpleConfigModifiers.cs b/src/Microsoft.TemplateEngine.Abstractions/ISimpleConfigModifiers.cs index 274476d2c44..8009202a93b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ISimpleConfigModifiers.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ISimpleConfigModifiers.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { [Obsolete("The interface is deprecated.")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplate.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplate.cs index 7518e49b078..1b5c832f3d2 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplate.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplate.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Abstractions diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs index c15da4909c3..4e03b48f03b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplateInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplateInfo.cs index 032e0dbb30f..88e4c8669ab 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplateInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplateLocator.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplateLocator.cs index 14f833543ed..6b037bd98b4 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplateLocator.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplateLocator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplateMetadata.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplateMetadata.cs index 5040bd9327a..178181c4531 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplateMetadata.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplateMetadata.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; diff --git a/src/Microsoft.TemplateEngine.Abstractions/ITemplateParameter.cs b/src/Microsoft.TemplateEngine.Abstractions/ITemplateParameter.cs index 4e6d5a6e24a..6fc165e9f9f 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/ITemplateParameter.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/ITemplateParameter.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/IValidationInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/IValidationInfo.cs index e5c6070d3bb..f18f3d9a38d 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IValidationInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IValidationInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { public interface IValidationInfo diff --git a/src/Microsoft.TemplateEngine.Abstractions/IVariableCollection.cs b/src/Microsoft.TemplateEngine.Abstractions/IVariableCollection.cs index 9f784e789fe..e4089dde884 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/IVariableCollection.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/IVariableCollection.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/CheckUpdateResult.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/CheckUpdateResult.cs index 23fb7b8e78e..827e6408270 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/CheckUpdateResult.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/CheckUpdateResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer @@ -18,7 +16,7 @@ private CheckUpdateResult(string? latestVersion, bool isLatest, IManagedTemplate TemplatePackage = templatePackage; LatestVersion = latestVersion; IsLatestVersion = isLatest; - Vulnerabilities = Array.Empty(); + Vulnerabilities = []; } private CheckUpdateResult( @@ -40,7 +38,7 @@ private CheckUpdateResult( /// /// True when the template package is already at the latest version. /// - /// In some cases the version installed can be higher then identified during update check. Since only installer can correctly compare the versions, the installer returns the result if the version is latest rather than letting the caller determine it using string comparison. + /// In some cases the version installed can be higher than identified during update check. Since only installer can correctly compare the versions, the installer returns the result if the version is latest rather than letting the caller determine it using string comparison. public bool IsLatestVersion { get; private set; } /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs index 853b3438d19..53ef5accc06 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallRequest.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallRequest.cs index 52a4fa8a912..1cf1df17d6e 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallRequest.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallRequest.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions.Installer { /// @@ -44,12 +41,12 @@ public InstallRequest(string identifier, string? version = null, string? install /// /// Could be folder name, NuGet PackageId, path to .nupkg... /// - public string PackageIdentifier { get; private set; } + public string PackageIdentifier { get; } /// /// Specific version to be installed or null to install latest. /// - public string? Version { get; private set; } + public string? Version { get; } /// /// Additional details, like NuGet Server(Source), that specific installer uses. diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallResult.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallResult.cs index 6338d6cabc5..dd6860e9e66 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallResult.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/InstallResult.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/TemplatePackageData.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/TemplatePackageData.cs index bf5a9a117cf..7a386b4e32a 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/TemplatePackageData.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/TemplatePackageData.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateRequest.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateRequest.cs index 1eb86b77ac1..63b4328d6e9 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateRequest.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateRequest.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateResult.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateResult.cs index 249e28aa296..299a9d305d3 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateResult.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/UpdateResult.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; namespace Microsoft.TemplateEngine.Abstractions.Installer diff --git a/src/Microsoft.TemplateEngine.Abstractions/Installer/VulnerabilityInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/Installer/VulnerabilityInfo.cs index 85aff7da4a7..68e6d0b5be2 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Installer/VulnerabilityInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Installer/VulnerabilityInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions.Installer { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Microsoft.TemplateEngine.Abstractions.csproj b/src/Microsoft.TemplateEngine.Abstractions/Microsoft.TemplateEngine.Abstractions.csproj index 1ed6e7aab05..618fe20653d 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Microsoft.TemplateEngine.Abstractions.csproj +++ b/src/Microsoft.TemplateEngine.Abstractions/Microsoft.TemplateEngine.Abstractions.csproj @@ -1,12 +1,19 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Contracts for extending Template Engine true true true + + + + + annotations + + @@ -14,4 +21,5 @@ + diff --git a/src/Microsoft.TemplateEngine.Abstractions/Mount/IDirectory.cs b/src/Microsoft.TemplateEngine.Abstractions/Mount/IDirectory.cs index 1395715b407..3dcb743209d 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Mount/IDirectory.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Mount/IDirectory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; - namespace Microsoft.TemplateEngine.Abstractions.Mount { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Mount/IFile.cs b/src/Microsoft.TemplateEngine.Abstractions/Mount/IFile.cs index b92d4c4d0ae..90bb7de0ad7 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Mount/IFile.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Mount/IFile.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; - namespace Microsoft.TemplateEngine.Abstractions.Mount { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs index a62364ec4c0..a3670f1fa8e 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.Mount { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointFactory.cs b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointFactory.cs index f71812d3e71..ebc75da55f7 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointFactory.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointFactory.cs @@ -15,7 +15,7 @@ public interface IMountPointFactory : IIdentifiedComponent /// /// Environment to be used. /// Mount points can be mounted inside each other. Pass in parent or null. - /// Valid that represents mount point. + /// Valid that represents mount point. /// Resulting mount point. /// true if mount point was successfully mounted. bool TryMount(IEngineEnvironmentSettings environmentSettings, IMountPoint? parent, string mountPointUri, out IMountPoint? mountPoint); diff --git a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointManager.cs b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointManager.cs index b5247d10b5e..42f6f11043a 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointManager.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointManager.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.Mount { [Obsolete("Use Microsoft.TemplateEngine.Utils.EngineEnvironmentSettingsExtensions.TryGetMountPoint")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/Parameters/DataSource.cs b/src/Microsoft.TemplateEngine.Abstractions/Parameters/DataSource.cs index e286cf1fec1..e8ee33cf772 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Parameters/DataSource.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Parameters/DataSource.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.Parameters { public enum DataSource diff --git a/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterDefinitionSet.cs b/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterDefinitionSet.cs index e0b2a537ad7..2e9c4efaf8b 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterDefinitionSet.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterDefinitionSet.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions.Parameters; /// @@ -27,21 +25,21 @@ public interface IParameterDefinitionSet : IReadOnlyList /// Gets the element that has the specified key in the read-only dictionary. /// The key to locate. /// The element that has the specified key in the read-only dictionary. - /// key is null. - /// The property is retrieved and key is not found. + /// key is null. + /// The property is retrieved and key is not found. ITemplateParameter this[string key] { get; } /// Determines whether the read-only dictionary contains an element that has the specified key. /// The key to locate. /// true if the read-only dictionary contains an element that has the specified key; otherwise, false. - /// key is null. + /// key is null. bool ContainsKey(string key); /// Gets the value that is associated with the specified key. /// The key to locate. /// When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized. - /// true if the object that implements the interface contains an element that has the specified key; otherwise, false. - /// key is null. + /// true if the object that implements the interface contains an element that has the specified key; otherwise, false. + /// key is null. bool TryGetValue(string key, out ITemplateParameter value); // End of definitions pulled from IReadOnlyDictionary diff --git a/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterSetData.cs b/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterSetData.cs index 6d6c3274aa3..a233b22c419 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterSetData.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Parameters/IParameterSetData.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions.Parameters; /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterDefinitionSet.cs b/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterDefinitionSet.cs index 5e7ebe027ff..941b8f7fea8 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterDefinitionSet.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterDefinitionSet.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using System.Collections.Generic; -using System.Linq; namespace Microsoft.TemplateEngine.Abstractions.Parameters { diff --git a/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterSetData.cs b/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterSetData.cs index 645caa63516..f5b61520d78 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterSetData.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/Parameters/ParameterSetData.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using System.Collections.Generic; -using System.Linq; namespace Microsoft.TemplateEngine.Abstractions.Parameters; @@ -63,7 +61,7 @@ public ParameterSetData(ITemplateInfo templateInfo, IReadOnlyDictionary public static IParameterSetData Empty => - new ParameterSetData(new ParameterDefinitionSet((IReadOnlyDictionary?)null), System.Array.Empty()); + new ParameterSetData(new ParameterDefinitionSet((IReadOnlyDictionary?)null), []); /// public IParameterDefinitionSet ParametersDefinition { get; } diff --git a/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IFileLastWriteTimeSource.cs b/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IFileLastWriteTimeSource.cs index 0ed9547ca56..e53a4ba187d 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IFileLastWriteTimeSource.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IFileLastWriteTimeSource.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem { [Obsolete("Use IPhysicalFileSystem properties instead.")] diff --git a/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IPhysicalFileSystem.cs b/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IPhysicalFileSystem.cs index 75aa4dcea68..09a6c402fc6 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IPhysicalFileSystem.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IPhysicalFileSystem.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; - namespace Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem { /// @@ -107,7 +103,7 @@ public interface IPhysicalFileSystem /// Creates new which monitors specified path and on any changes calls callback. /// To stop watching dispose returned object. /// - IDisposable WatchFileChanges(string filepath, FileSystemEventHandler fileChanged); + IDisposable WatchFileChanges(string filePath, FileSystemEventHandler fileChanged); /// /// Gets the last write time for the in UTC. @@ -126,7 +122,7 @@ public interface IPhysicalFileSystem void SetLastWriteTimeUtc(string file, DateTime lastWriteTimeUtc); /// - /// If target is a subpath of relativeTo a relative bath from relativeTo to subpath will be returned. + /// If target is a sub-path of relativeTo a relative bath from relativeTo to sub-path will be returned. /// /// Path to be converted to relative if possible. /// Base of the relative path to be returned. diff --git a/src/Microsoft.TemplateEngine.Abstractions/PublicAPI.Shipped.txt b/src/Microsoft.TemplateEngine.Abstractions/PublicAPI.Shipped.txt index 84c6ff42c78..83281993f10 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/PublicAPI.Shipped.txt +++ b/src/Microsoft.TemplateEngine.Abstractions/PublicAPI.Shipped.txt @@ -187,7 +187,7 @@ Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.Rea Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.ReadAllText(string! path) -> string! Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.SetFileAttributes(string! file, System.IO.FileAttributes attributes) -> void Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.SetLastWriteTimeUtc(string! file, System.DateTime lastWriteTimeUtc) -> void -Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.WatchFileChanges(string! filepath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! +Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.WatchFileChanges(string! filePath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem.IPhysicalFileSystem.WriteAllText(string! path, string! value) -> void Microsoft.TemplateEngine.Abstractions.TemplateFiltering.ITemplateMatchInfo Microsoft.TemplateEngine.Abstractions.TemplateFiltering.ITemplateMatchInfo.AddMatchDisposition(Microsoft.TemplateEngine.Abstractions.TemplateFiltering.MatchInfo! newDisposition) -> void @@ -232,7 +232,7 @@ const Microsoft.TemplateEngine.Abstractions.Installer.InstallerConstants.NuGetSo const Microsoft.TemplateEngine.Abstractions.TemplateFiltering.MatchInfo.BuiltIn.Constraint = "Constraint" -> string! Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource.DisplayName.get -> string! -Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource.GetBoundValueAsync(Microsoft.TemplateEngine.Abstractions.IEngineEnvironmentSettings! settings, string! bindname, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource.GetBoundValueAsync(Microsoft.TemplateEngine.Abstractions.IEngineEnvironmentSettings! settings, string! bindName, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource.RequiresPrefixMatch.get -> bool Microsoft.TemplateEngine.Abstractions.Components.IBindSymbolSource.SourcePrefix.get -> string? Microsoft.TemplateEngine.Abstractions.Components.ISdkInfoProvider diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/ITemplateMatchInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/ITemplateMatchInfo.cs index 5fa714ccebe..6ddc678f3ec 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/ITemplateMatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/ITemplateMatchInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Abstractions.TemplateFiltering { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchInfo.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchInfo.cs index a903abb43dd..f16470f5b71 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.Constraints; namespace Microsoft.TemplateEngine.Abstractions.TemplateFiltering diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchKind.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchKind.cs index 5686caa37e8..3ca6720d4ff 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchKind.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateFiltering/MatchKind.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.TemplateFiltering { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackage.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackage.cs index 4851c529883..2188d8cebb2 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackage.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackage.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Installer; namespace Microsoft.TemplateEngine.Abstractions.TemplatePackage diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs index 7f2260467bf..26ee140d58f 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions.Installer; namespace Microsoft.TemplateEngine.Abstractions.TemplatePackage diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackage.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackage.cs index 5760ef9f49f..d22e6ce7884 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackage.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackage.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Abstractions.TemplatePackage diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs index 926bf30f144..349affcb547 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Abstractions.TemplatePackage { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/TemplatePackage.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/TemplatePackage.cs index 02e15c62e5a..32194c1f8c9 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/TemplatePackage.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplatePackage/TemplatePackage.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions.TemplatePackage { /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedence.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedence.cs index 20774af9df5..e7c2e35f023 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedence.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedence.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions; /// diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedenceExtensions.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedenceExtensions.cs index 7746a511a19..1ef2c4b3744 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedenceExtensions.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPrecedenceExtensions.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions; public static class TemplateParameterPrecedenceExtensions diff --git a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPriority.cs b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPriority.cs index d872c317aff..d1c09692a5f 100644 --- a/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPriority.cs +++ b/src/Microsoft.TemplateEngine.Abstractions/TemplateParameterPriority.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Cli/README.md b/src/Microsoft.TemplateEngine.Cli/README.md deleted file mode 100644 index b9031ac2ee4..00000000000 --- a/src/Microsoft.TemplateEngine.Cli/README.md +++ /dev/null @@ -1 +0,0 @@ -The source code is moved to [dotnet/sdk](https://github.com/dotnet/sdk/tree/main/src/Cli/Microsoft.TemplateEngine.Cli). \ No newline at end of file diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IEncodingConfig.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IEncodingConfig.cs index 583705deb27..6a4f8843301 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IEncodingConfig.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IEncodingConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.Core.Contracts diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IEngineConfig.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IEngineConfig.cs index 6b8b5e0d08c..66dba22e6b4 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IEngineConfig.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IEngineConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IGlobalRunSpec.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IGlobalRunSpec.cs index dc592f4f95c..95b540f93cc 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IGlobalRunSpec.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IGlobalRunSpec.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Core.Contracts diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IKeysChangedEventArgs.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IKeysChangedEventArgs.cs index 1f126f64d3a..e20b8fe0127 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IKeysChangedEventArgs.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IKeysChangedEventArgs.cs @@ -3,7 +3,5 @@ namespace Microsoft.TemplateEngine.Core.Contracts { - public interface IKeysChangedEventArgs - { - } + public interface IKeysChangedEventArgs; } diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IOperation.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IOperation.cs index c600ec2da80..6adc734025b 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IOperation.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IOperation.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Contracts { public interface IOperation diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IOrchestrator.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IOrchestrator.cs index 8b01993eaa1..cc83c43e5bc 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IOrchestrator.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IOrchestrator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IProcessor.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IProcessor.cs index 61bca53d4b5..d565902f21b 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IProcessor.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IProcessor.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; - namespace Microsoft.TemplateEngine.Core.Contracts { public interface IProcessor diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IProcessorState.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IProcessorState.cs index 4394ed82b51..7dbfeec82a5 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IProcessorState.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IProcessorState.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; namespace Microsoft.TemplateEngine.Core.Contracts @@ -45,7 +44,7 @@ public interface IProcessorState /// The token to find. /// The length of the buffer after the token is found. /// The position in the buffer after the token is found. - /// True if token should be seeked through. + /// True if token should be sought through. void SeekSourceForwardUntil(ITokenTrie match, ref int bufferLength, ref int currentBufferPosition, bool consumeToken = false); /// @@ -57,7 +56,7 @@ public interface IProcessorState /// Seeks target stream backwards until is found. /// /// The token to find. - /// True if token should be seeked through. + /// True if token should be sought through. void SeekTargetBackUntil(ITokenTrie match, bool consumeToken = false); /// diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IRunSpec.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IRunSpec.cs index 9f761b05454..ab6f95b2813 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IRunSpec.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IRunSpec.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Contracts { public interface IRunSpec diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/ITokenConfig.cs b/src/Microsoft.TemplateEngine.Core.Contracts/ITokenConfig.cs index b4abdb2c312..3d545a52211 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/ITokenConfig.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/ITokenConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Text; namespace Microsoft.TemplateEngine.Core.Contracts diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/ITokenTrie.cs b/src/Microsoft.TemplateEngine.Core.Contracts/ITokenTrie.cs index 401a0dd2873..76917ce1d32 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/ITokenTrie.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/ITokenTrie.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Contracts { public interface ITokenTrie diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/IVariableConfig.cs b/src/Microsoft.TemplateEngine.Core.Contracts/IVariableConfig.cs index bfdffdc9ea6..426c96a3c76 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/IVariableConfig.cs +++ b/src/Microsoft.TemplateEngine.Core.Contracts/IVariableConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Contracts { public interface IVariableConfig diff --git a/src/Microsoft.TemplateEngine.Core.Contracts/Microsoft.TemplateEngine.Core.Contracts.csproj b/src/Microsoft.TemplateEngine.Core.Contracts/Microsoft.TemplateEngine.Core.Contracts.csproj index 91a1ebcd830..a5976a0745d 100644 --- a/src/Microsoft.TemplateEngine.Core.Contracts/Microsoft.TemplateEngine.Core.Contracts.csproj +++ b/src/Microsoft.TemplateEngine.Core.Contracts/Microsoft.TemplateEngine.Core.Contracts.csproj @@ -1,7 +1,7 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Contracts for extending Microsoft.TemplateEngine.Core true true @@ -10,4 +10,5 @@ + diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/BinaryScope.cs b/src/Microsoft.TemplateEngine.Core/Expressions/BinaryScope.cs index 5e16f2f3f70..41337b341fc 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/BinaryScope.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/BinaryScope.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Core.Expressions { public class BinaryScope : IEvaluable diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Converter.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Converter.cs index 1ad860e7842..0c678aa773b 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Converter.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Converter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Reflection; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Core.Expressions @@ -56,7 +54,7 @@ public static bool TryExecute(object? source, out T? result) return handlerResult.Value; } - if (typeof(T).GetTypeInfo().IsEnum && source is string s) + if (typeof(T).IsEnum && source is string s) { try { @@ -145,7 +143,7 @@ private class DoubleConverter : ConverterItem { if (source is string s) { - return ParserExtensions.DoubleTryParseСurrentOrInvariant(s, out result); + return ParserExtensions.DoubleTryParseCurrentOrInvariant(s, out result); } result = 0; diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/CppStyleEvaluatorDefinition.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/CppStyleEvaluatorDefinition.cs index e0fb2930c2b..efc8d17dfec 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/CppStyleEvaluatorDefinition.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/CppStyleEvaluatorDefinition.cs @@ -1,12 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Globalization; -using System.IO; -using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -20,20 +16,18 @@ public static class CppStyleEvaluatorDefinition { private const int ReservedTokenCount = 24; private const int ReservedTokenMaxIndex = ReservedTokenCount - 1; - private static readonly IOperationProvider[] NoOperationProviders = Array.Empty(); + private static readonly IOperationProvider[] NoOperationProviders = []; private static readonly char[] SupportedQuotes = { '"', '\'' }; public static bool EvaluateFromString(ILogger logger, string text, IVariableCollection variables) { - using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text))) - using (MemoryStream res = new MemoryStream()) - { - EngineConfig cfg = new EngineConfig(logger, variables); - IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); - int len = (int)ms.Length; - int pos = 0; - return Evaluate(state, ref len, ref pos, out bool faulted); - } + using MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text)); + using MemoryStream res = new MemoryStream(); + EngineConfig cfg = new EngineConfig(logger, variables); + IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); + int len = (int)ms.Length; + int pos = 0; + return Evaluate(state, ref len, ref pos, out bool faulted); } public static bool Evaluate(IProcessorState processor, ref int bufferLength, ref int currentBufferPosition, out bool faulted) @@ -533,7 +527,7 @@ private static bool EvaluateCondition(IReadOnlyList tokens, IReadOnlyL private static object? InferTypeAndConvertLiteral(string literal) { - //A propertly quoted string must be... + // A properly quoted string must be... // At least two characters long // Start and end with the same character // The character that the string starts with must be one of the supported quote kinds @@ -556,7 +550,7 @@ private static bool EvaluateCondition(IReadOnlyList tokens, IReadOnlyL if ((literal.Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) || literal.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)) - && ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out double literalDouble)) + && ParserExtensions.DoubleTryParseCurrentOrInvariant(literal, out double literalDouble)) { return literalDouble; } diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/Scope.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/Scope.cs index 668b8a58fe6..e3f9714155f 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/Scope.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/Scope.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Core.Expressions.Cpp diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/TokenFamily.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/TokenFamily.cs index 48059b5f351..86e914b6434 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/TokenFamily.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp/TokenFamily.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Core.Expressions.Cpp { [Flags] diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp2/Cpp2StyleEvaluatorDefinition.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp2/Cpp2StyleEvaluatorDefinition.cs index 2a289ce798c..3623b5f8eae 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Cpp2/Cpp2StyleEvaluatorDefinition.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Cpp2/Cpp2StyleEvaluatorDefinition.cs @@ -82,7 +82,7 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) { TokenTrie trie = new(); - //Logic + // Logic trie.AddToken(processor.Encoding.GetBytes("&&")); trie.AddToken(processor.Encoding.GetBytes("||")); trie.AddToken(processor.Encoding.GetBytes("!")); @@ -93,15 +93,15 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) trie.AddToken(processor.Encoding.GetBytes("==")); trie.AddToken(processor.Encoding.GetBytes("!=")); - //Braces + // Braces trie.AddToken(processor.Encoding.GetBytes("(")); trie.AddToken(processor.Encoding.GetBytes(")")); - //Whitespace + // Whitespace trie.AddToken(processor.Encoding.GetBytes(" ")); trie.AddToken(processor.Encoding.GetBytes("\t")); - //EOLs + // EOLs trie.AddToken(processor.Encoding.GetBytes("\r\n")); trie.AddToken(processor.Encoding.GetBytes("\n")); trie.AddToken(processor.Encoding.GetBytes("\r")); @@ -109,17 +109,17 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) // quotes trie.AddToken(processor.Encoding.GetBytes("'")); - //Shifts + // Shifts trie.AddToken(processor.Encoding.GetBytes("<<")); trie.AddToken(processor.Encoding.GetBytes(">>")); - //Maths + // Math operators trie.AddToken(processor.Encoding.GetBytes("+")); trie.AddToken(processor.Encoding.GetBytes("-")); trie.AddToken(processor.Encoding.GetBytes("*")); trie.AddToken(processor.Encoding.GetBytes("/")); - //Bitwise operators + // Bitwise operators trie.AddToken(processor.Encoding.GetBytes("&")); trie.AddToken(processor.Encoding.GetBytes("|")); diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/IOperatorMap.cs b/src/Microsoft.TemplateEngine.Core/Expressions/IOperatorMap.cs index 0f923fdfcd0..718929357a2 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/IOperatorMap.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/IOperatorMap.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Expressions { public interface IOperatorMap diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/MSBuild/MSBuildStyleEvaluatorDefinition.cs b/src/Microsoft.TemplateEngine.Core/Expressions/MSBuild/MSBuildStyleEvaluatorDefinition.cs index ae0424d1647..a3c195e3e5e 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/MSBuild/MSBuildStyleEvaluatorDefinition.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/MSBuild/MSBuildStyleEvaluatorDefinition.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Expressions.Shared; diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/OperatorSetBuilder.cs b/src/Microsoft.TemplateEngine.Core/Expressions/OperatorSetBuilder.cs index 609221d8808..aad9f9fc067 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/OperatorSetBuilder.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/OperatorSetBuilder.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Expressions { public class OperatorSetBuilder : IOperatorMap diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/ScopeBuilder.cs b/src/Microsoft.TemplateEngine.Core/Expressions/ScopeBuilder.cs index 09c839aba73..eb712fbcc34 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/ScopeBuilder.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/ScopeBuilder.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Util; diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/CoreConverters.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/CoreConverters.cs index 44f9e620273..f9594947f73 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/CoreConverters.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/CoreConverters.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Globalization; namespace Microsoft.TemplateEngine.Core.Expressions.Shared diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/SharedEvaluatorDefinition.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/SharedEvaluatorDefinition.cs index e8bed869263..c1c09a090c6 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/SharedEvaluatorDefinition.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/SharedEvaluatorDefinition.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -22,7 +18,7 @@ public abstract class SharedEvaluatorDefinition private static readonly IOperatorMap Map = Instance.GenerateMap(); private static readonly bool DereferenceInLiteralsSetting = Instance.DereferenceInLiterals; private static readonly string NullToken = Instance.NullTokenValue; - private static readonly IOperationProvider[] NoOperationProviders = Array.Empty(); + private static readonly IOperationProvider[] NoOperationProviders = []; protected abstract string NullTokenValue { get; } @@ -60,15 +56,13 @@ public static bool EvaluateFromString(ILogger logger, string text, IVariableColl /// A boolean value indicating the result of the evaluation. public static bool EvaluateFromString(ILogger logger, string text, IVariableCollection variables, out string? faultedMessage, HashSet? referencedVariablesKeys = null) { - using (MemoryStream ms = new(Encoding.UTF8.GetBytes(text))) - using (MemoryStream res = new()) - { - EngineConfig cfg = new(logger, variables); - IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); - int len = (int)ms.Length; - int pos = 0; - return Evaluate(state, ref len, ref pos, out faultedMessage, referencedVariablesKeys, true); - } + using MemoryStream ms = new(Encoding.UTF8.GetBytes(text)); + using MemoryStream res = new(); + EngineConfig cfg = new(logger, variables); + IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); + int len = (int)ms.Length; + int pos = 0; + return Evaluate(state, ref len, ref pos, out faultedMessage, referencedVariablesKeys, true); } /// @@ -88,16 +82,14 @@ public static bool EvaluateFromString(ILogger logger, string text, IVariableColl out string? evaluableExpressionError, HashSet referencedVariablesKeys) { - using (MemoryStream ms = new(Encoding.UTF8.GetBytes(text))) - using (MemoryStream res = new()) - { - EngineConfig cfg = new(logger, variables); - IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); - int len = (int)ms.Length; - int pos = 0; - - return GetEvaluableExpression(state, ref len, ref pos, out evaluableExpressionError, referencedVariablesKeys); - } + using MemoryStream ms = new(Encoding.UTF8.GetBytes(text)); + using MemoryStream res = new(); + EngineConfig cfg = new(logger, variables); + IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); + int len = (int)ms.Length; + int pos = 0; + + return GetEvaluableExpression(state, ref len, ref pos, out evaluableExpressionError, referencedVariablesKeys); } protected static int Compare(object? left, object? right) @@ -116,7 +108,7 @@ protected static int Compare(object? left, object? right) ?? AttemptBooleanComparison(left, right) ?? AttemptVersionComparison(left, right) ?? AttemptMultiValueComparison(left, right) - ?? AttemptLexographicComparison(left, right) + ?? AttemptLexicographicComparison(left, right) ?? AttemptComparableComparison(left, right) ?? 0; } @@ -236,7 +228,7 @@ private static bool Evaluate( return null; } - private static int? AttemptLexographicComparison(object? left, object? right) + private static int? AttemptLexicographicComparison(object? left, object? right) { if (left is not string ls || right is not string rs) { diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/XmlStyleConverters.cs b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/XmlStyleConverters.cs index 0bfbc76596a..eb6d7a60901 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/Shared/XmlStyleConverters.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/Shared/XmlStyleConverters.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Globalization; namespace Microsoft.TemplateEngine.Core.Expressions.Shared diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/UnaryScope.cs b/src/Microsoft.TemplateEngine.Core/Expressions/UnaryScope.cs index 32c439943b6..af928f505a1 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/UnaryScope.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/UnaryScope.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Core.Expressions { public class UnaryScope : IEvaluable diff --git a/src/Microsoft.TemplateEngine.Core/Expressions/VisualBasic/VisualBasicStyleEvaluatorDefintion.cs b/src/Microsoft.TemplateEngine.Core/Expressions/VisualBasic/VisualBasicStyleEvaluatorDefintion.cs index aa9bdd90f64..b70336bc083 100644 --- a/src/Microsoft.TemplateEngine.Core/Expressions/VisualBasic/VisualBasicStyleEvaluatorDefintion.cs +++ b/src/Microsoft.TemplateEngine.Core/Expressions/VisualBasic/VisualBasicStyleEvaluatorDefintion.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Expressions.Shared; @@ -85,7 +84,7 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) { TokenTrie trie = new TokenTrie(); - //Logic + // Logic trie.AddToken(processor.Encoding.GetBytes("And")); trie.AddToken(processor.Encoding.GetBytes("AndAlso")); trie.AddToken(processor.Encoding.GetBytes("Or")); @@ -99,15 +98,15 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) trie.AddToken(processor.Encoding.GetBytes("<>")); trie.AddToken(processor.Encoding.GetBytes("Xor")); - //Braces + // Braces trie.AddToken(processor.Encoding.GetBytes("(")); trie.AddToken(processor.Encoding.GetBytes(")")); - //Whitespace + // Whitespace trie.AddToken(processor.Encoding.GetBytes(" ")); trie.AddToken(processor.Encoding.GetBytes("\t")); - //EOLs + // EOLs trie.AddToken(processor.Encoding.GetBytes("\r\n")); trie.AddToken(processor.Encoding.GetBytes("\n")); trie.AddToken(processor.Encoding.GetBytes("\r")); @@ -115,11 +114,11 @@ protected override ITokenTrie GetSymbols(IProcessorState processor) // quotes trie.AddToken(processor.Encoding.GetBytes("'")); - //Shifts + // Shifts trie.AddToken(processor.Encoding.GetBytes("<<")); trie.AddToken(processor.Encoding.GetBytes(">>")); - //Maths + // Math operators trie.AddToken(processor.Encoding.GetBytes("+")); trie.AddToken(processor.Encoding.GetBytes("-")); trie.AddToken(processor.Encoding.GetBytes("*")); diff --git a/src/Microsoft.TemplateEngine.Core/FileChange.cs b/src/Microsoft.TemplateEngine.Core/FileChange.cs index 2dcb38d95e0..1f5083d25be 100644 --- a/src/Microsoft.TemplateEngine.Core/FileChange.cs +++ b/src/Microsoft.TemplateEngine.Core/FileChange.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Core @@ -13,7 +12,7 @@ public FileChange(string sourceRelativePath, string targetRelativePath, ChangeKi SourceRelativePath = sourceRelativePath; TargetRelativePath = targetRelativePath; ChangeKind = changeKind; - Contents = contents ?? Array.Empty(); + Contents = contents ?? []; } public string SourceRelativePath { get; } diff --git a/src/Microsoft.TemplateEngine.Core/KeysChangedEventArgs.cs b/src/Microsoft.TemplateEngine.Core/KeysChangedEventArgs.cs index 6515bc94491..7661d387ca1 100644 --- a/src/Microsoft.TemplateEngine.Core/KeysChangedEventArgs.cs +++ b/src/Microsoft.TemplateEngine.Core/KeysChangedEventArgs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Core diff --git a/src/Microsoft.TemplateEngine.Core/LocalizableStrings.Designer.cs b/src/Microsoft.TemplateEngine.Core/LocalizableStrings.Designer.cs deleted file mode 100644 index d9ecdd87d68..00000000000 --- a/src/Microsoft.TemplateEngine.Core/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Core { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Core.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Encountered following error when parsing and evaluating expression:. - /// - internal static string Error_Evaluation_Expression { - get { - return ResourceManager.GetString("Error_Evaluation_Expression", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unexpected substring after parsed expression:. - /// - internal static string Error_Evaluation_Expression_Substring { - get { - return ResourceManager.GetString("Error_Evaluation_Expression_Substring", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.TemplateEngine.Core/Matching/Trie.cs b/src/Microsoft.TemplateEngine.Core/Matching/Trie.cs index 2af6f6b3611..948c036a4e1 100644 --- a/src/Microsoft.TemplateEngine.Core/Matching/Trie.cs +++ b/src/Microsoft.TemplateEngine.Core/Matching/Trie.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Matching { public class Trie diff --git a/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluationDriver.cs b/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluationDriver.cs index 3e4dbf20648..5bd97a146b0 100644 --- a/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluationDriver.cs +++ b/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluationDriver.cs @@ -54,8 +54,7 @@ public TrieEvaluationDriver(TrieEvaluator trie) if (expectedShift == 0) { int actualShift = originalSequenceNumber - _sequenceNumber - 1; - int compensation = actualShift - expectedShift; - bufferPosition -= compensation; + bufferPosition -= actualShift; } } } diff --git a/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluator.cs b/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluator.cs index fa5228fdc7e..a0b7469e17d 100644 --- a/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluator.cs +++ b/src/Microsoft.TemplateEngine.Core/Matching/TrieEvaluator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Matching { public class TrieEvaluator diff --git a/src/Microsoft.TemplateEngine.Core/Matching/TrieNode.cs b/src/Microsoft.TemplateEngine.Core/Matching/TrieNode.cs index 032c57ecaa8..9e8a1d00b1a 100644 --- a/src/Microsoft.TemplateEngine.Core/Matching/TrieNode.cs +++ b/src/Microsoft.TemplateEngine.Core/Matching/TrieNode.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Matching { public class TrieNode : Trie diff --git a/src/Microsoft.TemplateEngine.Core/Matching/TriePath.cs b/src/Microsoft.TemplateEngine.Core/Matching/TriePath.cs index 3258f132b95..b0de9b89f3a 100644 --- a/src/Microsoft.TemplateEngine.Core/Matching/TriePath.cs +++ b/src/Microsoft.TemplateEngine.Core/Matching/TriePath.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Core.Matching { internal class TriePath diff --git a/src/Microsoft.TemplateEngine.Core/Microsoft.TemplateEngine.Core.csproj b/src/Microsoft.TemplateEngine.Core/Microsoft.TemplateEngine.Core.csproj index 703bb07b770..1d1030ee839 100644 --- a/src/Microsoft.TemplateEngine.Core/Microsoft.TemplateEngine.Core.csproj +++ b/src/Microsoft.TemplateEngine.Core/Microsoft.TemplateEngine.Core.csproj @@ -1,12 +1,18 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Common operations for instantiating templates using forward-only input stream operations true true + + + + annotations + + @@ -14,21 +20,12 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + + diff --git a/src/Microsoft.TemplateEngine.Core/Operations/BalancedNesting.cs b/src/Microsoft.TemplateEngine.Core/Operations/BalancedNesting.cs index 4fbcfa3f3c6..f3aaa7d7c7f 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/BalancedNesting.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/BalancedNesting.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Core.Contracts; @@ -23,7 +22,6 @@ public class BalancedNesting : IOperationProvider private readonly ITokenConfig _startToken; private readonly ITokenConfig _realEndToken; private readonly ITokenConfig _pseudoEndToken; - private readonly string? _id; private readonly string? _resetFlag; private readonly bool _initialState; @@ -32,12 +30,12 @@ public BalancedNesting(ITokenConfig startToken, ITokenConfig realEndToken, IToke _startToken = startToken; _realEndToken = realEndToken; _pseudoEndToken = pseudoEndToken; - _id = id; + Id = id; _resetFlag = resetFlag; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processorState) { @@ -45,36 +43,33 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState IToken realEndToken = _realEndToken.ToToken(encoding); IToken pseudoEndToken = _pseudoEndToken.ToToken(encoding); - return new Impl(startToken, realEndToken, pseudoEndToken, _id, _resetFlag, _initialState); + return new Implementation(startToken, realEndToken, pseudoEndToken, Id, _resetFlag, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { // the order they're added to this.Tokens in the constructor must be the same as this! private const int StartTokenIndex = 0; private const int RealEndTokenIndex = 1; private const int PseudoEndTokenIndex = 2; - private readonly IToken _startToken; private readonly IToken _realEndToken; - private readonly IToken _psuedoEndToken; - private readonly string? _id; + private readonly IToken _pseudoEndToken; private readonly string? _resetFlag; private int _depth; - public Impl(IToken start, IToken realEnd, IToken pseudoEnd, string? id, string? resetFlag, bool initialState) + public Implementation(IToken start, IToken realEnd, IToken pseudoEnd, string? id, string? resetFlag, bool initialState) { - _startToken = start; _realEndToken = realEnd; - _psuedoEndToken = pseudoEnd; - _id = id; + _pseudoEndToken = pseudoEnd; + Id = id; _resetFlag = resetFlag; - Tokens = new[] { _startToken, _realEndToken, _psuedoEndToken }; + Tokens = new[] { start, _realEndToken, _pseudoEndToken }; _depth = 0; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } - public string? Id => _id; + public string? Id { get; } public IReadOnlyList Tokens { get; } @@ -83,7 +78,7 @@ public Impl(IToken start, IToken realEnd, IToken pseudoEnd, string? id, string? public int HandleMatch(IProcessorState processor, int bufferLength, ref int currentBufferPosition, int token) { // check if this operation has been reset. If so, set _depth = 0 - // this fixes the reset problem, but not the trailing unbalanced pseduo comment problem, i.e. it won't turn this: + // this fixes the reset problem, but not the trailing unbalanced pseudo comment problem, i.e. it won't turn this: // @@ -114,7 +109,7 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr if (_depth == 0 && token == PseudoEndTokenIndex) { processor.WriteToTarget(_realEndToken.Value, _realEndToken.Start, _realEndToken.Length); - return _psuedoEndToken.Length; // the source buffer needs to skip over this token. + return _pseudoEndToken.Length; // the source buffer needs to skip over this token. } else { diff --git a/src/Microsoft.TemplateEngine.Core/Operations/Conditional.cs b/src/Microsoft.TemplateEngine.Core/Operations/Conditional.cs index b5dc23d7c5f..11f12db7f9f 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/Conditional.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/Conditional.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; @@ -31,35 +29,30 @@ public class Conditional : IOperationProvider // must be > the highest token type index private const int TokenTypeModulus = 10; - private readonly ConditionEvaluator _evaluator; - private readonly bool _wholeLine; - private readonly bool _trimWhitespace; - private readonly ConditionalTokens _tokens; - private readonly string? _id; private readonly bool _initialState; public Conditional(ConditionalTokens tokenVariants, bool wholeLine, bool trimWhitespace, ConditionEvaluator evaluator, string? id, bool initialState) { - _trimWhitespace = trimWhitespace; - _wholeLine = wholeLine; - _evaluator = evaluator; - _tokens = tokenVariants; - _id = id; + TrimWhitespace = trimWhitespace; + WholeLine = wholeLine; + Evaluator = evaluator; + Tokens = tokenVariants; + Id = id; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } - public bool WholeLine => _wholeLine; + public bool WholeLine { get; } - public bool TrimWhitespace => _trimWhitespace; + public bool TrimWhitespace { get; } - public ConditionEvaluator Evaluator => _evaluator; + public ConditionEvaluator Evaluator { get; } - public ConditionalTokens Tokens => _tokens; + public ConditionalTokens Tokens { get; } /// - /// Returns the numner of elements in the longest of the token variant lists. + /// Returns the number of elements in the longest of the token variant lists. /// private int LongestTokenVariantListSize { @@ -94,7 +87,7 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState AddTokensOfTypeToTokenListAndTrie(trie, tokens, Tokens.ActionableElseTokens, ElseTokenActionableBaseIndex, encoding); AddTokensOfTypeToTokenListAndTrie(trie, tokens, Tokens.ActionableElseIfTokens, ElseIfTokenActionableBaseIndex, encoding); - return new Impl(this, tokens, trie, _id, _initialState); + return new Implementation(this, tokens, trie, Id, _initialState); } /// @@ -130,24 +123,23 @@ private void AddTokensOfTypeToTokenListAndTrie(ITokenTrie trie, List tok } } - private class Impl : IOperation + private class Implementation : IOperation { private readonly Conditional _definition; private readonly Stack _pendingCompletion = new Stack(); private readonly ITokenTrie _trie; - private readonly string? _id; private EvaluationState? _current; - public Impl(Conditional definition, IReadOnlyList tokens, ITokenTrie trie, string? id, bool initialState) + public Implementation(Conditional definition, IReadOnlyList tokens, ITokenTrie trie, string? id, bool initialState) { _trie = trie; _definition = definition; Tokens = tokens; - _id = id; + Id = id; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } - public string? Id => _id; + public string? Id { get; } public IReadOnlyList Tokens { get; } @@ -164,11 +156,11 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr // conditional has not started, or this is the "if" if (_current != null || IsTokenIndexOfType(token, IfTokenBaseIndex) || IsTokenIndexOfType(token, IfTokenActionableBaseIndex)) { - if (_definition._wholeLine) + if (_definition.WholeLine) { processor.SeekTargetBackUntil(processor.EncodingConfig.LineEndings); } - else if (_definition._trimWhitespace) + else if (_definition.TrimWhitespace) { processor.TrimWhitespace(false, true, ref bufferLength, ref currentBufferPosition); } @@ -237,11 +229,11 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr _current = null; } - if (_definition._wholeLine) + if (_definition.WholeLine) { processor.SeekSourceForwardUntil(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition, consumeToken: true); } - else if (_definition._trimWhitespace) + else if (_definition.TrimWhitespace) { processor.TrimWhitespace(true, false, ref bufferLength, ref currentBufferPosition); } @@ -268,11 +260,11 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr _current = null; } - if (_definition._wholeLine) + if (_definition.WholeLine) { processor.SeekSourceForwardUntil(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition, consumeToken: false); } - else if (_definition._trimWhitespace) + else if (_definition.TrimWhitespace) { processor.TrimWhitespace(true, false, ref bufferLength, ref currentBufferPosition); } @@ -320,7 +312,7 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr } _current.BranchTaken = true; - processor.WhitespaceHandler(ref bufferLength, ref currentBufferPosition, wholeLine: _definition._wholeLine, trim: _definition._trimWhitespace); + processor.WhitespaceHandler(ref bufferLength, ref currentBufferPosition, wholeLine: _definition.WholeLine, trim: _definition.TrimWhitespace); return 0; } else @@ -430,12 +422,12 @@ private bool SeekToToken(IProcessorState processor, ref int bufferLength, ref in private class EvaluationState { - private readonly Impl _impl; + private readonly Implementation _implementation; private bool _branchTaken; - public EvaluationState(Impl impl) + public EvaluationState(Implementation implementation) { - _impl = impl; + _implementation = implementation; ActionableOperationsEnabled = false; } @@ -451,7 +443,7 @@ public void ToggleActionableOperations(bool enabled, IProcessorState processor) { ActionableOperationsEnabled = enabled; - foreach (string otherOptionDisableFlag in _impl._definition.Tokens.ActionableOperations) + foreach (string otherOptionDisableFlag in _implementation._definition.Tokens.ActionableOperations) { processor.Config.Flags[otherOptionDisableFlag] = enabled; } @@ -459,7 +451,7 @@ public void ToggleActionableOperations(bool enabled, IProcessorState processor) internal bool Evaluate(IProcessorState processor, ref int bufferLength, ref int currentBufferPosition) { - BranchTaken = _impl._definition._evaluator(processor, ref bufferLength, ref currentBufferPosition, out bool faulted); + BranchTaken = _implementation._definition.Evaluator(processor, ref bufferLength, ref currentBufferPosition, out bool faulted); return BranchTaken; } } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/ConditionalTokens.cs b/src/Microsoft.TemplateEngine.Core/Operations/ConditionalTokens.cs index e28cd9dbe33..edb6f6a76bd 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/ConditionalTokens.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/ConditionalTokens.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Core.Operations @@ -11,14 +9,14 @@ public class ConditionalTokens { public ConditionalTokens() { - IfTokens = Array.Empty(); - ElseTokens = Array.Empty(); - ElseIfTokens = Array.Empty(); - EndIfTokens = Array.Empty(); - ActionableIfTokens = Array.Empty(); - ActionableElseTokens = Array.Empty(); - ActionableElseIfTokens = Array.Empty(); - ActionableOperations = Array.Empty(); + IfTokens = []; + ElseTokens = []; + ElseIfTokens = []; + EndIfTokens = []; + ActionableIfTokens = []; + ActionableElseTokens = []; + ActionableElseIfTokens = []; + ActionableOperations = []; } public IReadOnlyList IfTokens { get; set; } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/ExpandVariables.cs b/src/Microsoft.TemplateEngine.Core/Operations/ExpandVariables.cs index b9ab5315a1b..ac71b9434df 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/ExpandVariables.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/ExpandVariables.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -11,36 +10,33 @@ public class ExpandVariables : IOperationProvider { public static readonly string OperationName = "expandvariables"; - private readonly string? _id; private readonly bool _initialState; public ExpandVariables(string? id, bool initialState) { - _id = id; + Id = id; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processor) { - return new Impl(processor, _id, _initialState); + return new Implementation(processor, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { - private readonly string? _id; - - public Impl(IProcessorState processor, string? id, bool initialState) + public Implementation(IProcessorState processor, string? id, bool initialState) { Tokens = processor.EncodingConfig.VariableKeys; - _id = id; + Id = id; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } public IReadOnlyList Tokens { get; } - public string? Id => _id; + public string? Id { get; } public bool IsInitialStateOn { get; } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/Include.cs b/src/Microsoft.TemplateEngine.Core/Operations/Include.cs index 0fe8da917b2..c616a04dab8 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/Include.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/Include.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Util; @@ -14,8 +11,6 @@ public class Include : IOperationProvider { public static readonly string OperationName = "include"; - private readonly string? _id; - private readonly bool _initialState; public Include(ITokenConfig startToken, ITokenConfig endToken, Func sourceStreamOpener, string? id, bool initialState) @@ -23,7 +18,7 @@ public Include(ITokenConfig startToken, ITokenConfig endToken, Func SourceStreamOpener { get; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processorState) { @@ -41,27 +36,26 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState IToken endTokenBytes = EndToken.ToToken(encoding); TokenTrie endTokenMatcher = new TokenTrie(); endTokenMatcher.AddToken(endTokenBytes); - return new Impl(tokenBytes, endTokenMatcher, this, _id, _initialState); + return new Implementation(tokenBytes, endTokenMatcher, this, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly Include _source; private readonly ITokenTrie _endTokenMatcher; - private readonly string? _id; - public Impl(IToken token, ITokenTrie endTokenMatcher, Include source, string? id, bool initialState) + public Implementation(IToken token, ITokenTrie endTokenMatcher, Include source, string? id, bool initialState) { Tokens = new[] { token }; _source = source; _endTokenMatcher = endTokenMatcher; - _id = id; + Id = id; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } public IReadOnlyList Tokens { get; } - public string? Id => _id; + public string? Id { get; } public bool IsInitialStateOn { get; } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/InlineMarkupConditional.cs b/src/Microsoft.TemplateEngine.Core/Operations/InlineMarkupConditional.cs index b40a0cd2db5..754359de34c 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/InlineMarkupConditional.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/InlineMarkupConditional.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Util; @@ -13,13 +9,12 @@ namespace Microsoft.TemplateEngine.Core.Operations { public class InlineMarkupConditional : IOperationProvider { - private readonly string? _id; private readonly bool _initialState; public InlineMarkupConditional(MarkupTokens tokens, bool wholeLine, bool trimWhitespace, ConditionEvaluator evaluator, string variableFormat, string? id, bool initialState) { Tokens = tokens; - _id = id; + Id = id; Evaluator = evaluator; WholeLine = wholeLine; TrimWhitespace = trimWhitespace; @@ -29,7 +24,7 @@ public InlineMarkupConditional(MarkupTokens tokens, bool wholeLine, bool trimWhi public ConditionEvaluator Evaluator { get; } - public string? Id => _id; + public string? Id { get; } public MarkupTokens Tokens { get; } @@ -69,10 +64,10 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState closeCommentToken); IReadOnlyList start = new[] { Tokens.OpenConditionExpression.ToToken(processorState.Encoding) }; - return new Impl(this, start, structureTrie, closeConditionTrie, scanBackTrie, mapping, _id, _initialState); + return new Implementation(this, start, structureTrie, closeConditionTrie, scanBackTrie, mapping, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly ITokenTrie _closeConditionTrie; private readonly InlineMarkupConditional _definition; @@ -80,7 +75,7 @@ private class Impl : IOperation private readonly ITokenTrie _scanBackTrie; private readonly ITokenTrie _structureTrie; - internal Impl(InlineMarkupConditional definition, IReadOnlyList tokens, ITokenTrie structureTrie, ITokenTrie closeConditionTrie, ITokenTrie scanBackTrie, MarkupTokenMapping mapping, string? id, bool initialState) + internal Implementation(InlineMarkupConditional definition, IReadOnlyList tokens, ITokenTrie structureTrie, ITokenTrie closeConditionTrie, ITokenTrie scanBackTrie, MarkupTokenMapping mapping, string? id, bool initialState) { _definition = definition; Id = id; @@ -110,7 +105,7 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr ScanToCloseCondition(processor, conditionBytes, ref bufferLength, ref currentBufferPosition); byte[] condition = conditionBytes.ToArray(); EngineConfig adjustedConfig = new EngineConfig(processor.Config.Logger, processor.Config.Whitespaces, processor.Config.LineEndings, processor.Config.Variables, _definition.VariableFormat); - IProcessorState localState = new ProcessorState(new MemoryStream(condition), new MemoryStream(), conditionBytes.Count, int.MaxValue, adjustedConfig, Array.Empty()); + IProcessorState localState = new ProcessorState(new MemoryStream(condition), new MemoryStream(), conditionBytes.Count, int.MaxValue, adjustedConfig, []); int pos = 0; int len = conditionBytes.Count; diff --git a/src/Microsoft.TemplateEngine.Core/Operations/Phase.cs b/src/Microsoft.TemplateEngine.Core/Operations/Phase.cs index 465eda9d27a..745893880a5 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/Phase.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/Phase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Core.Operations diff --git a/src/Microsoft.TemplateEngine.Core/Operations/PhasedOperation.cs b/src/Microsoft.TemplateEngine.Core/Operations/PhasedOperation.cs index 46731b156f2..c6815c102fd 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/PhasedOperation.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/PhasedOperation.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -11,17 +9,16 @@ namespace Microsoft.TemplateEngine.Core.Operations public class PhasedOperation : IOperationProvider { private readonly IReadOnlyList _config; - private readonly string? _id; private readonly bool _initialState; public PhasedOperation(string? id, IReadOnlyList config, bool initialState) { - _id = id; + Id = id; _config = config; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processorState) { @@ -86,24 +83,24 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState } } - return new Impl(this, tokens, currentTarget, _initialState); + return new Implementation(this, tokens, currentTarget, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly PhasedOperation _definition; private readonly IReadOnlyList _entryPoints; private SpecializedPhase? _currentPhase; - public Impl(PhasedOperation definition, IReadOnlyList config, IReadOnlyList entryPoints, bool initialState) + public Implementation(PhasedOperation definition, IReadOnlyList config, IReadOnlyList entryPoints, bool initialState) { _definition = definition; Tokens = config; _entryPoints = entryPoints; - IsInitialStateOn = string.IsNullOrEmpty(_definition._id) || initialState; + IsInitialStateOn = string.IsNullOrEmpty(_definition.Id) || initialState; } - public string? Id => _definition._id; + public string? Id => _definition.Id; public IReadOnlyList Tokens { get; } @@ -112,7 +109,7 @@ public Impl(PhasedOperation definition, IReadOnlyList config, IReadOnlyL public int HandleMatch(IProcessorState processor, int bufferLength, ref int currentBufferPosition, int token) { IReadOnlyList nextPhases = _currentPhase?.Next ?? _entryPoints; - SpecializedPhase match = nextPhases.FirstOrDefault(x => x.Match == token); + SpecializedPhase? match = nextPhases.FirstOrDefault(x => x.Match == token); if (match != null) { @@ -147,12 +144,5 @@ public SpecializedPhase() public List ResetsWith { get; } } - - private class SpecializedPhasedOperationConfig - { - public IReadOnlyList? EntryPoints { get; set; } - - public IReadOnlyList? Tokens { get; set; } - } } } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/Region.cs b/src/Microsoft.TemplateEngine.Core/Operations/Region.cs index 48b491d2341..d9a945f4878 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/Region.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/Region.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -17,7 +16,6 @@ public class Region : IOperationProvider private readonly bool _toggle; private readonly bool _wholeLine; private readonly bool _trimWhitespace; - private readonly string? _id; private readonly bool _initialState; public Region(ITokenConfig start, ITokenConfig end, bool include, bool wholeLine, bool trimWhitespace, string? id, bool initialState) @@ -28,29 +26,28 @@ public Region(ITokenConfig start, ITokenConfig end, bool include, bool wholeLine _end = end; _include = include; _toggle = _start.Equals(_end); - _id = id; + Id = id; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processorState) { IToken startToken = _start.ToToken(encoding); IToken endToken = _end.ToToken(encoding); - return new Impl(this, startToken, endToken, _include, _toggle, _id, _initialState); + return new Implementation(this, startToken, endToken, _include, _toggle, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly IToken _endToken; private readonly bool _includeRegion; private readonly bool _startAndEndAreSame; private readonly Region _definition; - private readonly string? _id; private bool _waitingForEnd; - public Impl(Region owner, IToken startToken, IToken endToken, bool include, bool toggle, string? id, bool initialState) + public Implementation(Region owner, IToken startToken, IToken endToken, bool include, bool toggle, string? id, bool initialState) { _definition = owner; _endToken = endToken; @@ -58,13 +55,13 @@ public Impl(Region owner, IToken startToken, IToken endToken, bool include, bool _startAndEndAreSame = toggle; Tokens = toggle ? new[] { startToken } : new[] { startToken, endToken }; - _id = id; + Id = id; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } public IReadOnlyList Tokens { get; } - public string? Id => _id; + public string? Id { get; } public bool IsInitialStateOn { get; } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/Replacement.cs b/src/Microsoft.TemplateEngine.Core/Operations/Replacement.cs index a4998648498..9990d530cd9 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/Replacement.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/Replacement.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -14,18 +12,17 @@ public class Replacement : IOperationProvider private readonly ITokenConfig _match; private readonly string? _replaceWith; - private readonly string? _id; private readonly bool _initialState; public Replacement(ITokenConfig match, string? replaceWith, string? id, bool initialState) { _match = match; _replaceWith = replaceWith; - _id = id; + Id = id; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public IOperation GetOperation(Encoding encoding, IProcessorState processorState) { @@ -37,27 +34,26 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState return null!; } - return new Impl(token, replaceWith, _id, _initialState); + return new Implementation(token, replaceWith, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly byte[] _replacement; private readonly IToken _token; - private readonly string? _id; - public Impl(IToken token, byte[] replaceWith, string? id, bool initialState) + public Implementation(IToken token, byte[] replaceWith, string? id, bool initialState) { _replacement = replaceWith; _token = token; - _id = id; + Id = id; Tokens = new[] { token }; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } public IReadOnlyList Tokens { get; } - public string? Id => _id; + public string? Id { get; } public bool IsInitialStateOn { get; } diff --git a/src/Microsoft.TemplateEngine.Core/Operations/SetFlag.cs b/src/Microsoft.TemplateEngine.Core/Operations/SetFlag.cs index 9ecaa8162b5..301deea36c0 100644 --- a/src/Microsoft.TemplateEngine.Core/Operations/SetFlag.cs +++ b/src/Microsoft.TemplateEngine.Core/Operations/SetFlag.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -11,7 +10,6 @@ public class SetFlag : IOperationProvider { public static readonly string OperationName = "flags"; - private readonly string? _id; private readonly bool _initialState; public SetFlag(string? name, ITokenConfig on, ITokenConfig off, ITokenConfig onNoEmit, ITokenConfig offNoEmit, string? id, bool initialState, bool? @default = null) @@ -22,11 +20,11 @@ public SetFlag(string? name, ITokenConfig on, ITokenConfig off, ITokenConfig onN OnNoEmit = onNoEmit; OffNoEmit = offNoEmit; Default = @default; - _id = id; + Id = id; _initialState = initialState; } - public string? Id => _id; + public string? Id { get; } public string? Name { get; } @@ -55,25 +53,24 @@ public IOperation GetOperation(Encoding encoding, IProcessorState processorState processorState.Config.Flags[Name!] = Default.Value; } - return new Impl(this, tokens, _id, _initialState); + return new Implementation(this, tokens, Id, _initialState); } - private class Impl : IOperation + private class Implementation : IOperation { private readonly SetFlag _owner; - private readonly string? _id; - public Impl(SetFlag owner, IReadOnlyList tokens, string? id, bool initialState) + public Implementation(SetFlag owner, IReadOnlyList tokens, string? id, bool initialState) { _owner = owner; Tokens = tokens; - _id = id; + Id = id; IsInitialStateOn = string.IsNullOrEmpty(id) || initialState; } public IReadOnlyList Tokens { get; } - public string? Id => _id; + public string? Id { get; } public bool IsInitialStateOn { get; } @@ -95,7 +92,7 @@ public int HandleMatch(IProcessorState processor, int bufferLength, ref int curr } else { - // consume the entire line when not emitting. Otherwise the newlines on the falg tokens get emitted + // consume the entire line when not emitting. Otherwise the newlines on the flag tokens get emitted processor.SeekSourceForwardUntil(processor.EncodingConfig.LineEndings, ref bufferLength, ref currentBufferPosition, consumeToken: true); } diff --git a/src/Microsoft.TemplateEngine.Core/TokenConfig.cs b/src/Microsoft.TemplateEngine.Core/TokenConfig.cs index 8bb751dec7c..d2917c5b2ba 100644 --- a/src/Microsoft.TemplateEngine.Core/TokenConfig.cs +++ b/src/Microsoft.TemplateEngine.Core/TokenConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -45,9 +44,9 @@ public TokenConfig OnlyIfBefore(string? suffix) public IToken ToToken(Encoding encoding) { - byte[] pre = string.IsNullOrEmpty(After) ? Array.Empty() : encoding.GetBytes(After); - byte[] post = string.IsNullOrEmpty(Before) ? Array.Empty() : encoding.GetBytes(Before); - byte[] core = string.IsNullOrEmpty(Value) ? Array.Empty() : encoding.GetBytes(Value); + byte[] pre = string.IsNullOrEmpty(After) ? [] : encoding.GetBytes(After); + byte[] post = string.IsNullOrEmpty(Before) ? [] : encoding.GetBytes(Before); + byte[] core = string.IsNullOrEmpty(Value) ? [] : encoding.GetBytes(Value); byte[] buffer = new byte[pre.Length + core.Length + post.Length]; diff --git a/src/Microsoft.TemplateEngine.Core/TokenConfigExtensions.cs b/src/Microsoft.TemplateEngine.Core/TokenConfigExtensions.cs index a55ba8171e7..06d4aec60b0 100644 --- a/src/Microsoft.TemplateEngine.Core/TokenConfigExtensions.cs +++ b/src/Microsoft.TemplateEngine.Core/TokenConfigExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Core/Util/CombinedStream.cs b/src/Microsoft.TemplateEngine.Core/Util/CombinedStream.cs index a5389c6391a..c6831aac35e 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/CombinedStream.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/CombinedStream.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; - namespace Microsoft.TemplateEngine.Core.Util { internal class CombinedStream : Stream diff --git a/src/Microsoft.TemplateEngine.Core/Util/EncodingConfig.cs b/src/Microsoft.TemplateEngine.Core/Util/EncodingConfig.cs index bae5a2b7e5e..cac1f60a682 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/EncodingConfig.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/EncodingConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; @@ -58,12 +56,12 @@ public EncodingConfig(IEngineConfig config, Encoding encoding) private void ExpandVariables(IEngineConfig config, Encoding encoding) { - foreach (string key in config.Variables.Keys) + foreach (var item in config.Variables) { - string formattedKey = string.Format(config.VariableFormatString, key); + string formattedKey = string.Format(config.VariableFormatString, item.Key); IToken keyBytes = formattedKey.Token(encoding); _variableKeys.Add(keyBytes); - _values[Variables.AddToken(keyBytes)] = () => config.Variables[key]; + _values[Variables.AddToken(keyBytes)] = () => item.Value; } } } diff --git a/src/Microsoft.TemplateEngine.Core/Util/EncodingUtil.cs b/src/Microsoft.TemplateEngine.Core/Util/EncodingUtil.cs index 8d09356fc46..8dada041968 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/EncodingUtil.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/EncodingUtil.cs @@ -16,7 +16,7 @@ public static Encoding Detect(byte[] buffer, int currentBufferLength, out byte[] if (currentBufferLength == 0) { //File is zero length - pick something - bom = System.Array.Empty(); + bom = []; return Encoding.UTF8; } @@ -65,7 +65,7 @@ public static Encoding Detect(byte[] buffer, int currentBufferLength, out byte[] } //Fallback to UTF-8 - bom = System.Array.Empty(); + bom = []; return Encoding.UTF8; } } diff --git a/src/Microsoft.TemplateEngine.Core/Util/EngineConfig.cs b/src/Microsoft.TemplateEngine.Core/Util/EngineConfig.cs index 78ecb4a0ee6..45683700d18 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/EngineConfig.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/EngineConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Core/Util/Orchestrator.cs b/src/Microsoft.TemplateEngine.Core/Util/Orchestrator.cs index f8dd5abe248..09afaae2647 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/Orchestrator.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/Orchestrator.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -34,12 +30,10 @@ public void Run(string runSpecPath, IDirectory sourceDir, string targetDir) EngineConfig config = new EngineConfig(_logger, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor processor = Processor.Create(config, spec.Operations); stream.Position = 0; - using (MemoryStream ms = new MemoryStream()) - { - processor.Run(stream, ms); - ms.Position = 0; - spec = RunSpecLoader(ms); - } + using MemoryStream ms = new MemoryStream(); + processor.Run(stream, ms); + ms.Position = 0; + spec = RunSpecLoader(ms); } RunInternal(sourceDir, targetDir, spec); @@ -54,12 +48,10 @@ public IReadOnlyList GetFileChanges(string runSpecPath, IDirectory EngineConfig config = new EngineConfig(_logger, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor processor = Processor.Create(config, spec.Operations); stream.Position = 0; - using (MemoryStream ms = new MemoryStream()) - { - processor.Run(stream, ms); - ms.Position = 0; - spec = RunSpecLoader(ms); - } + using MemoryStream ms = new MemoryStream(); + processor.Run(stream, ms); + ms.Position = 0; + spec = RunSpecLoader(ms); } return GetFileChangesInternal(sourceDir, targetDir, spec); @@ -132,14 +124,10 @@ private IReadOnlyList GetFileChangesInternal(IDirectory sourceDir, { string sourceRel = file.PathRelativeTo(sourceDir); string fileName = Path.GetFileName(sourceRel); - bool checkingDirWithPlaceholderFile = false; - if (spec.IgnoreFileNames.Contains(fileName)) - { - // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. - // The change checking / reporting is different, setting this variable tracks it. - checkingDirWithPlaceholderFile = true; - } + // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. + // The change checking / reporting is different, setting this variable tracks it. + bool checkingDirWithPlaceholderFile = spec.IgnoreFileNames.Contains(fileName); foreach (IPathMatcher include in spec.Include) { @@ -207,14 +195,10 @@ private void RunInternal(IDirectory sourceDir, string targetDir, IGlobalRunSpec { string sourceRel = file.PathRelativeTo(sourceDir); string fileName = Path.GetFileName(sourceRel); - bool checkingDirWithPlaceholderFile = false; - if (spec.IgnoreFileNames.Contains(fileName)) - { - // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. - // The change checking / reporting is different, setting this variable tracks it. - checkingDirWithPlaceholderFile = true; - } + // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. + // The change checking / reporting is different, setting this variable tracks it. + bool checkingDirWithPlaceholderFile = spec.IgnoreFileNames.Contains(fileName); foreach (IPathMatcher include in spec.Include) { @@ -254,11 +238,9 @@ private void RunInternal(IDirectory sourceDir, string targetDir, IGlobalRunSpec { string targetPath = CreateTargetDir(_fileSystem, sourceRel, targetDir, spec); - using (Stream sourceStream = file.OpenRead()) - using (Stream targetStream = _fileSystem.CreateFile(targetPath)) - { - sourceStream.CopyTo(targetStream); - } + using Stream sourceStream = file.OpenRead(); + using Stream targetStream = _fileSystem.CreateFile(targetPath); + sourceStream.CopyTo(targetStream); } } @@ -287,23 +269,21 @@ private void ProcessFile(IFile sourceFile, string sourceRel, string targetDir, I try { - using (Stream source = sourceFile.OpenRead()) - using (Stream target = _fileSystem.CreateFile(targetPath)) + using Stream source = sourceFile.OpenRead(); + using Stream target = _fileSystem.CreateFile(targetPath); + if (!customBufferSize) + { + runner.Run(source, target); + } + else { - if (!customBufferSize) + if (!customFlushThreshold) { - runner.Run(source, target); + runner.Run(source, target, bufferSize); } else { - if (!customFlushThreshold) - { - runner.Run(source, target, bufferSize); - } - else - { - runner.Run(source, target, bufferSize, flushThreshold); - } + runner.Run(source, target, bufferSize, flushThreshold); } } } diff --git a/src/Microsoft.TemplateEngine.Core/Util/Processor.cs b/src/Microsoft.TemplateEngine.Core/Util/Processor.cs index 17ce766a5da..312462926f1 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/Processor.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/Processor.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Core/Util/ProcessorState.cs b/src/Microsoft.TemplateEngine.Core/Util/ProcessorState.cs index 9538a84ad41..7a6371d9b31 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/ProcessorState.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/ProcessorState.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Matching; diff --git a/src/Microsoft.TemplateEngine.Core/Util/StreamProxy.cs b/src/Microsoft.TemplateEngine.Core/Util/StreamProxy.cs index 24338927c11..44c68e1513e 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/StreamProxy.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/StreamProxy.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; - namespace Microsoft.TemplateEngine.Core.Util { /// diff --git a/src/Microsoft.TemplateEngine.Core/Util/TokenTrie.cs b/src/Microsoft.TemplateEngine.Core/Util/TokenTrie.cs index 7b5f79a7309..34874ff3afe 100644 --- a/src/Microsoft.TemplateEngine.Core/Util/TokenTrie.cs +++ b/src/Microsoft.TemplateEngine.Core/Util/TokenTrie.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Matching; diff --git a/src/Microsoft.TemplateEngine.Core/ValueReadEventArgs.cs b/src/Microsoft.TemplateEngine.Core/ValueReadEventArgs.cs index ce7dd340480..2eaefe84425 100644 --- a/src/Microsoft.TemplateEngine.Core/ValueReadEventArgs.cs +++ b/src/Microsoft.TemplateEngine.Core/ValueReadEventArgs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Core diff --git a/src/Microsoft.TemplateEngine.Core/VariableCollection.cs b/src/Microsoft.TemplateEngine.Core/VariableCollection.cs index 4bf33d6f09f..f05c12e6a15 100644 --- a/src/Microsoft.TemplateEngine.Core/VariableCollection.cs +++ b/src/Microsoft.TemplateEngine.Core/VariableCollection.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; @@ -12,7 +9,7 @@ namespace Microsoft.TemplateEngine.Core { public class VariableCollection : IVariableCollection, IMonitoredVariableCollection { - private static readonly IEnumerable NoKeys = Array.Empty(); + private static readonly IEnumerable NoKeys = []; private readonly IDictionary _values; private IVariableCollection? _parent; diff --git a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettings.cs b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettings.cs index 082cf948aee..4c129082e94 100644 --- a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettings.cs +++ b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettings.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; @@ -77,7 +72,7 @@ public async Task> GetInstalledTemplatePackag if (!_environmentSettings.Host.FileSystem.FileExists(_globalSettingsFile)) { - return Array.Empty(); + return []; } for (int i = 0; i < FileReadWriteRetries; i++) diff --git a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsData.cs b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsData.cs index f72c5f9098a..6a380483ee0 100644 --- a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsData.cs +++ b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsData.cs @@ -1,14 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Installer; using Newtonsoft.Json; namespace Microsoft.TemplateEngine.Edge.BuiltInManagedProvider { /// - /// Used just to serialize/deserilize data to/from settings.json file. + /// Used just to serialize/deserialize data to/from settings.json file. /// internal sealed class GlobalSettingsData { diff --git a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProvider.cs b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProvider.cs index 64384c94f66..f5a245d257e 100644 --- a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProvider.cs +++ b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProvider.cs @@ -1,27 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; -using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Edge.BuiltInManagedProvider { internal class GlobalSettingsTemplatePackageProvider : IManagedTemplatePackageProvider, IDisposable { private const string DebugLogCategory = "Installer"; - private readonly string _globalSettingsFilePath; - private readonly string _packagesFolder; - private readonly IEngineEnvironmentSettings _environmentSettings; private readonly ILogger _logger; private readonly Dictionary _installersByGuid = new Dictionary(); private readonly Dictionary _installersByName = new Dictionary(); @@ -30,17 +20,17 @@ internal class GlobalSettingsTemplatePackageProvider : IManagedTemplatePackagePr public GlobalSettingsTemplatePackageProvider(GlobalSettingsTemplatePackageProviderFactory factory, IEngineEnvironmentSettings settings) { Factory = factory ?? throw new ArgumentNullException(nameof(factory)); - _environmentSettings = settings ?? throw new ArgumentNullException(nameof(settings)); + IEngineEnvironmentSettings environmentSettings = settings ?? throw new ArgumentNullException(nameof(settings)); _logger = settings.Host.LoggerFactory.CreateLogger(); - _packagesFolder = Path.Combine(settings.Paths.GlobalSettingsDir, "packages"); - if (!settings.Host.FileSystem.DirectoryExists(_packagesFolder)) + string packagesFolder = Path.Combine(settings.Paths.GlobalSettingsDir, "packages"); + if (!settings.Host.FileSystem.DirectoryExists(packagesFolder)) { - settings.Host.FileSystem.CreateDirectory(_packagesFolder); + settings.Host.FileSystem.CreateDirectory(packagesFolder); } foreach (var installerFactory in settings.Components.OfType()) { - var installer = installerFactory.CreateInstaller(settings, _packagesFolder); + var installer = installerFactory.CreateInstaller(settings, packagesFolder); //this provider cannot work with installers that do not implement ISerializableInstaller if (installer is ISerializableInstaller) @@ -50,8 +40,8 @@ public GlobalSettingsTemplatePackageProvider(GlobalSettingsTemplatePackageProvid } } - _globalSettingsFilePath = Path.Combine(_environmentSettings.Paths.GlobalSettingsDir, "packages.json"); - _globalSettings = new GlobalSettings(_environmentSettings, _globalSettingsFilePath); + string globalSettingsFilePath = Path.Combine(environmentSettings.Paths.GlobalSettingsDir, "packages.json"); + _globalSettings = new GlobalSettings(environmentSettings, globalSettingsFilePath); // We can't just add "SettingsChanged+=TemplatePackagesChanged", because TemplatePackagesChanged is null at this time. _globalSettings.SettingsChanged += () => TemplatePackagesChanged?.Invoke(); } @@ -147,7 +137,7 @@ public async Task> InstallAsync(IEnumerable()); + []); } if (installersThatCanInstall.Count > 1) { @@ -155,7 +145,7 @@ public async Task> InstallAsync(IEnumerable()); + []); } IInstaller installer = installersThatCanInstall[0]; @@ -230,7 +220,7 @@ private async Task UpdateAsync(List packages, (InstallerErrorCode result, string message) = await EnsureInstallPrerequisites(packages, updateRequest.TemplatePackage.Identifier, updateRequest.Version, updateRequest.TemplatePackage.Installer, cancellationToken, update: true).ConfigureAwait(false); if (result != InstallerErrorCode.Success) { - return UpdateResult.CreateFailure(updateRequest, result, message, Array.Empty()); + return UpdateResult.CreateFailure(updateRequest, result, message, []); } UpdateResult updateResult = await updateRequest.TemplatePackage.Installer.UpdateAsync(updateRequest, provider: this, cancellationToken).ConfigureAwait(false); @@ -312,7 +302,7 @@ private async Task InstallAsync(List package forceUpdate: installRequest.Force).ConfigureAwait(false); if (result != InstallerErrorCode.Success) { - return InstallResult.CreateFailure(installRequest, result, message, Array.Empty()); + return InstallResult.CreateFailure(installRequest, result, message, []); } InstallResult installResult = await installer.InstallAsync(installRequest, this, cancellationToken).ConfigureAwait(false); diff --git a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProviderFactory.cs b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProviderFactory.cs index e0bac9a784a..fcca4b2ee9a 100644 --- a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProviderFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/GlobalSettingsTemplatePackageProviderFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; diff --git a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/IGlobalSettings.cs b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/IGlobalSettings.cs index 5d01ebaf5d0..5b5ec7768a0 100644 --- a/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/IGlobalSettings.cs +++ b/src/Microsoft.TemplateEngine.Edge/BuiltInManagedProvider/IGlobalSettings.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions.Installer; namespace Microsoft.TemplateEngine.Edge.BuiltInManagedProvider @@ -21,7 +17,7 @@ internal interface IGlobalSettings event Action SettingsChanged; /// - /// Returns uncached list of the template packages. + /// Returns non-cached list of the template packages. /// Task> GetInstalledTemplatePackagesAsync(CancellationToken cancellationToken); diff --git a/src/Microsoft.TemplateEngine.Edge/Components.cs b/src/Microsoft.TemplateEngine.Edge/Components.cs index 25c9bfb503e..3b0d9e4c983 100644 --- a/src/Microsoft.TemplateEngine.Edge/Components.cs +++ b/src/Microsoft.TemplateEngine.Edge/Components.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; using Microsoft.TemplateEngine.Abstractions.Constraints; diff --git a/src/Microsoft.TemplateEngine.Edge/Components/EnvironmentVariablesBindSource.cs b/src/Microsoft.TemplateEngine.Edge/Components/EnvironmentVariablesBindSource.cs index 63eb7b9309c..2c504224abe 100644 --- a/src/Microsoft.TemplateEngine.Edge/Components/EnvironmentVariablesBindSource.cs +++ b/src/Microsoft.TemplateEngine.Edge/Components/EnvironmentVariablesBindSource.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; @@ -17,7 +14,7 @@ public sealed class EnvironmentVariablesBindSource : IBindSymbolSource { int IPrioritizedComponent.Priority => 0; - string? IBindSymbolSource.SourcePrefix => "env"; + string IBindSymbolSource.SourcePrefix => "env"; bool IBindSymbolSource.RequiresPrefixMatch => false; @@ -25,19 +22,19 @@ public sealed class EnvironmentVariablesBindSource : IBindSymbolSource string IBindSymbolSource.DisplayName => LocalizableStrings.EnvironmentVariablesBindSource_Name; - Task IBindSymbolSource.GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindname, CancellationToken cancellationToken) + Task IBindSymbolSource.GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindName, CancellationToken cancellationToken) { settings.Host.Logger.LogDebug( "[{0}]: Retrieving bound value for '{1}'.", nameof(EnvironmentVariablesBindSource), - bindname); + bindName); - string? result = settings.Environment.GetEnvironmentVariable(bindname); + string? result = settings.Environment.GetEnvironmentVariable(bindName); settings.Host.Logger.LogDebug( "[{0}]: Retrieved bound value for '{1}': '{2}'.", nameof(EnvironmentVariablesBindSource), - bindname, + bindName, result ?? ""); return Task.FromResult(result); } diff --git a/src/Microsoft.TemplateEngine.Edge/Components/HostParametersBindSource.cs b/src/Microsoft.TemplateEngine.Edge/Components/HostParametersBindSource.cs index 2f0e3b820f5..0c8c886b447 100644 --- a/src/Microsoft.TemplateEngine.Edge/Components/HostParametersBindSource.cs +++ b/src/Microsoft.TemplateEngine.Edge/Components/HostParametersBindSource.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; @@ -17,7 +14,7 @@ public sealed class HostParametersBindSource : IBindSymbolSource { int IPrioritizedComponent.Priority => 100; - string? IBindSymbolSource.SourcePrefix => "host"; + string IBindSymbolSource.SourcePrefix => "host"; bool IBindSymbolSource.RequiresPrefixMatch => false; @@ -25,19 +22,19 @@ public sealed class HostParametersBindSource : IBindSymbolSource string IBindSymbolSource.DisplayName => LocalizableStrings.HostParametersBindSource_Name; - Task IBindSymbolSource.GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindname, CancellationToken cancellationToken) + Task IBindSymbolSource.GetBoundValueAsync(IEngineEnvironmentSettings settings, string bindName, CancellationToken cancellationToken) { settings.Host.Logger.LogDebug( "[{0}]: Retrieving bound value for '{1}'.", nameof(HostParametersBindSource), - bindname); + bindName); - settings.Host.TryGetHostParamDefault(bindname, out string? newValue); + settings.Host.TryGetHostParamDefault(bindName, out string? newValue); settings.Host.Logger.LogDebug( "[{0}]: Retrieved bound value for '{1}': '{2}'.", nameof(HostParametersBindSource), - bindname, + bindName, newValue ?? ""); return Task.FromResult(newValue); diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/ConfigurationException.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/ConfigurationException.cs index e94975da844..5ad19eed698 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/ConfigurationException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/ConfigurationException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.Constraints; namespace Microsoft.TemplateEngine.Edge.Constraints diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/ConstraintsExtensions.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/ConstraintsExtensions.cs index b195ec81dc8..5f18d34b7ed 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/ConstraintsExtensions.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/ConstraintsExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; @@ -23,7 +20,7 @@ public static IEnumerable ParseArrayOfConstraintStrings(this string? arg if (token.Type == JTokenType.String) { - return new[] { token.Value() ?? throw new ConfigurationException(string.Format(LocalizableStrings.Constaint_Error_ArgumentHasEmptyString, args)) }; + return new[] { token.Value() ?? throw new ConfigurationException(string.Format(LocalizableStrings.Constraint_Error_ArgumentHasEmptyString, args)) }; } JArray array = token.ToConstraintsJArray(args, true); @@ -32,7 +29,7 @@ public static IEnumerable ParseArrayOfConstraintStrings(this string? arg { if (string.IsNullOrEmpty(value)) { - throw new ConfigurationException(string.Format(LocalizableStrings.Constaint_Error_ArgumentHasEmptyString, args)); + throw new ConfigurationException(string.Format(LocalizableStrings.Constraint_Error_ArgumentHasEmptyString, args)); } return value!; @@ -43,7 +40,7 @@ public static IEnumerable ParseArrayOfConstraintStrings(this string? arg /// Attempts to parse input configuration string (presumably string or json array of strings) into enumeration of JObjects. /// /// Input configuration string. - /// Enumeration of parsed Jobject tokens. + /// Enumeration of parsed JObject tokens. /// Thrown on unexpected input - not a valid json array or an empty array. public static IEnumerable ParseArrayOfConstraintJObjects(this string? args) { @@ -52,12 +49,12 @@ public static IEnumerable ParseArrayOfConstraintJObjects(this string? a return array.Select(value => { - if (value is not JObject jobj) + if (value is not JObject jObj) { throw new ConfigurationException(string.Format(LocalizableStrings.Constraint_Error_InvalidJsonArray_Objects, args)); } - return jobj; + return jObj; }); } diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/HostConstraint.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/HostConstraint.cs index 505e6956a10..29741375b44 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/HostConstraint.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/HostConstraint.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Utils; @@ -76,14 +71,14 @@ private static IEnumerable ParseArgs(string? args) { List hostInformation = new List(); - foreach (JObject jobj in args.ParseArrayOfConstraintJObjects()) + foreach (JObject jObj in args.ParseArrayOfConstraintJObjects()) { - string? hostName = jobj.ToString("hostname"); - string? version = jobj.ToString("version"); + string? hostName = jObj.ToString("hostname"); + string? version = jObj.ToString("version"); if (string.IsNullOrWhiteSpace(hostName)) { - throw new ConfigurationException(string.Format(LocalizableStrings.HostConstraint_Error_MissingMandatoryProperty, jobj, "hostname")); + throw new ConfigurationException(string.Format(LocalizableStrings.HostConstraint_Error_MissingMandatoryProperty, jObj, "hostname")); } if (string.IsNullOrWhiteSpace(version)) { diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/OSConstraint.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/OSConstraint.cs index 778d75ac513..0f6d6986574 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/OSConstraint.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/OSConstraint.cs @@ -1,12 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/SdkVersionConstraintFactory.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/SdkVersionConstraintFactory.cs index c856358d5a3..133b12e86be 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/SdkVersionConstraintFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/SdkVersionConstraintFactory.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; using Microsoft.TemplateEngine.Abstractions.Constraints; diff --git a/src/Microsoft.TemplateEngine.Edge/Constraints/WorkloadConstraintFactory.cs b/src/Microsoft.TemplateEngine.Edge/Constraints/WorkloadConstraintFactory.cs index 79e4aa3f293..e42441e81a5 100644 --- a/src/Microsoft.TemplateEngine.Edge/Constraints/WorkloadConstraintFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Constraints/WorkloadConstraintFactory.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; diff --git a/src/Microsoft.TemplateEngine.Edge/DefaultEnvironment.cs b/src/Microsoft.TemplateEngine.Edge/DefaultEnvironment.cs index f8e3f420133..55df8a7ae55 100644 --- a/src/Microsoft.TemplateEngine.Edge/DefaultEnvironment.cs +++ b/src/Microsoft.TemplateEngine.Edge/DefaultEnvironment.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge @@ -59,9 +56,9 @@ protected static IReadOnlyDictionary FetchEnvironmentVariables() Dictionary variables = new Dictionary(StringComparer.OrdinalIgnoreCase); IDictionary env = Environment.GetEnvironmentVariables(); - foreach (string key in env.Keys.OfType()) + foreach (string key in env.Keys.Cast()) { - variables[key] = (env[key] as string) ?? string.Empty; + variables[key] = (string)env[key]; } return variables; diff --git a/src/Microsoft.TemplateEngine.Edge/DefaultPathInfo.cs b/src/Microsoft.TemplateEngine.Edge/DefaultPathInfo.cs index de5c600b36b..232679a40fd 100644 --- a/src/Microsoft.TemplateEngine.Edge/DefaultPathInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/DefaultPathInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using System.Runtime.InteropServices; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs b/src/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs index 98b198a587e..c2def792a6d 100644 --- a/src/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs +++ b/src/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.TemplateEngine.Abstractions; @@ -13,11 +11,9 @@ namespace Microsoft.TemplateEngine.Edge { public class DefaultTemplateEngineHost : ITemplateEngineHost { - private static readonly IReadOnlyList<(Type, IIdentifiedComponent)> NoComponents = Array.Empty<(Type, IIdentifiedComponent)>(); + private static readonly IReadOnlyList<(Type, IIdentifiedComponent)> NoComponents = []; private readonly IReadOnlyDictionary _hostDefaults; private readonly IReadOnlyList<(Type InterfaceType, IIdentifiedComponent Instance)> _hostBuiltInComponents; - private readonly ILoggerFactory _loggerFactory; - private readonly ILogger _logger; public DefaultTemplateEngineHost( string hostIdentifier, @@ -35,23 +31,27 @@ public DefaultTemplateEngineHost( FallbackHostTemplateConfigNames = fallbackHostTemplateConfigNames ?? new List(); loggerFactory ??= NullLoggerFactory.Instance; - _loggerFactory = loggerFactory; - _logger = _loggerFactory.CreateLogger("Template Engine") ?? NullLogger.Instance; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger("Template Engine"); + + WorkingDirectory = Environment.CurrentDirectory; } public IPhysicalFileSystem FileSystem { get; private set; } public string HostIdentifier { get; } + public string WorkingDirectory { get; } + public IReadOnlyList FallbackHostTemplateConfigNames { get; } public string Version { get; } public virtual IReadOnlyList<(Type InterfaceType, IIdentifiedComponent Instance)> BuiltInComponents => _hostBuiltInComponents; - public ILogger Logger => _logger; + public ILogger Logger { get; } - public ILoggerFactory LoggerFactory => _loggerFactory; + public ILoggerFactory LoggerFactory { get; } // stub that will be built out soon. public virtual bool TryGetHostParamDefault(string paramName, out string? value) @@ -61,6 +61,9 @@ public virtual bool TryGetHostParamDefault(string paramName, out string? value) case "HostIdentifier": value = HostIdentifier; return true; + case "WorkingDirectory": + value = WorkingDirectory; + return true; } return _hostDefaults.TryGetValue(paramName, out value); @@ -73,7 +76,7 @@ public void VirtualizeDirectory(string path) public void Dispose() { - _loggerFactory?.Dispose(); + LoggerFactory?.Dispose(); } #region Obsoleted diff --git a/src/Microsoft.TemplateEngine.Edge/EngineEnvironmentSettings.cs b/src/Microsoft.TemplateEngine.Edge/EngineEnvironmentSettings.cs index 5acae4cffa3..9a904a3bbff 100644 --- a/src/Microsoft.TemplateEngine.Edge/EngineEnvironmentSettings.cs +++ b/src/Microsoft.TemplateEngine.Edge/EngineEnvironmentSettings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge.Settings; @@ -25,7 +24,7 @@ public sealed class EngineEnvironmentSettings : IEngineEnvironmentSettings /// /// implementation of to use. If not specified, will be used. /// implementation of to use. If not specified, built-in implementation will be used. - /// implememtation of to use. If not specified, will be used (if is used, settings location will be overriden as mentioned in description).
+ /// implementation of to use. If not specified, will be used (if is used, settings location will be overridden as mentioned in description).
/// If is specified, do not provide . /// public EngineEnvironmentSettings( diff --git a/src/Microsoft.TemplateEngine.Edge/FilterableTemplateInfo.cs b/src/Microsoft.TemplateEngine.Edge/FilterableTemplateInfo.cs index ca184ee10b3..9056525f2b0 100644 --- a/src/Microsoft.TemplateEngine.Edge/FilterableTemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/FilterableTemplateInfo.cs @@ -3,8 +3,6 @@ #nullable disable -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -76,9 +74,9 @@ private FilterableTemplateInfo(ITemplateInfo source) public IReadOnlyDictionary TagsCollection { get; private set; } - IReadOnlyList ITemplateMetadata.PostActions => _source?.PostActions ?? Array.Empty(); + IReadOnlyList ITemplateMetadata.PostActions => _source?.PostActions ?? []; - IReadOnlyList ITemplateMetadata.Constraints => _source?.Constraints ?? Array.Empty(); + IReadOnlyList ITemplateMetadata.Constraints => _source?.Constraints ?? []; public static FilterableTemplateInfo FromITemplateInfo(ITemplateInfo source) { diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstaller.cs b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstaller.cs index 430e4b83e11..bd366077c6d 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstaller.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstaller.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; @@ -61,7 +56,7 @@ public Task InstallAsync(InstallRequest installRequest, IManagedT return Task.FromResult(InstallResult.CreateSuccess( installRequest, new FolderManagedTemplatePackage(_settings, this, provider, installRequest.PackageIdentifier, DateTime.UtcNow), - Array.Empty())); + [])); } else { @@ -70,7 +65,7 @@ public Task InstallAsync(InstallRequest installRequest, IManagedT installRequest, InstallerErrorCode.PackageNotFound, string.Format(LocalizableStrings.FolderInstaller_InstallResult_Error_FolderDoesNotExist, installRequest.PackageIdentifier), - Array.Empty())); + [])); } } @@ -103,7 +98,7 @@ public Task UpdateAsync(UpdateRequest updateRequest, IManagedTempl return Task.FromResult(UpdateResult.CreateSuccess( updateRequest, new FolderManagedTemplatePackage(_settings, this, provider, updateRequest.TemplatePackage.Identifier, DateTime.UtcNow), - Array.Empty())); + [])); } } } diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstallerFactory.cs b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstallerFactory.cs index 48313294eb4..f9b312faaeb 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstallerFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderInstallerFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderManagedTemplatePackage.cs b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderManagedTemplatePackage.cs index 57a377cb90e..57119414563 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderManagedTemplatePackage.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/Folder/FolderManagedTemplatePackage.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/DownloadException.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/DownloadException.cs index 339e75bb886..8e812cd70e9 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/DownloadException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/DownloadException.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Installers.NuGet { internal class DownloadException : Exception diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetPackageException.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetPackageException.cs index 991c38b2d62..f1f13b5fffb 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetPackageException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetPackageException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Edge.Installers.NuGet { internal class InvalidNuGetPackageException : Exception diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetSourceException.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetSourceException.cs index 5f521c20210..5e53733c2c4 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetSourceException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/InvalidNuGetSourceException.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Installers.NuGet { internal class InvalidNuGetSourceException : Exception diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/PackageNotFoundException.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/PackageNotFoundException.cs index ed65be6551c..7650842598d 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/PackageNotFoundException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/PackageNotFoundException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using NuGet.Versioning; namespace Microsoft.TemplateEngine.Edge.Installers.NuGet diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/VulnerablePackageException.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/VulnerablePackageException.cs index b91f29c1297..faccc7cef83 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/VulnerablePackageException.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/Exceptions/VulnerablePackageException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Installer; namespace Microsoft.TemplateEngine.Edge.Installers.NuGet diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IDownloader.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IDownloader.cs index e00d2ff7397..d2592914d44 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IDownloader.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IDownloader.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions.Installer; namespace Microsoft.TemplateEngine.Edge.Installers.NuGet diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IUpdateChecker.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IUpdateChecker.cs index 2904bb2c8de..acf90a25a28 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IUpdateChecker.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/IUpdateChecker.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading; -using System.Threading.Tasks; using static Microsoft.TemplateEngine.Edge.Installers.NuGet.NuGetApiPackageManager; namespace Microsoft.TemplateEngine.Edge.Installers.NuGet diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstaller.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstaller.cs index 13c07891ad5..485946c15fe 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstaller.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstaller.cs @@ -1,12 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; @@ -149,27 +143,27 @@ public async Task> GetLatestVersionAsync( package, InstallerErrorCode.PackageNotFound, string.Format(LocalizableStrings.NuGetInstaller_Error_FailedToReadPackage, e.PackageIdentifier, string.Join(", ", e.SourcesList)), - Array.Empty()); + []); } catch (InvalidNuGetSourceException e) { string message = e.SourcesList == null || !e.SourcesList.Any() - ? LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources_None - : string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources, string.Join(", ", e.SourcesList)); + ? LocalizableStrings.NuGetInstaller_InstallResult_Error_InvalidSources_None + : string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_InvalidSources, string.Join(", ", e.SourcesList)); return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.InvalidSource, message, - Array.Empty()); + []); } catch (OperationCanceledException) { return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.GenericError, - LocalizableStrings.NuGetInstaller_InstallResut_Error_OperationCancelled, - Array.Empty()); + LocalizableStrings.NuGetInstaller_InstallResult_Error_OperationCancelled, + []); } catch (VulnerablePackageException e) { @@ -185,8 +179,8 @@ public async Task> GetLatestVersionAsync( return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.GenericError, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_UpdateCheckGeneric, package.DisplayName, e.Message), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_UpdateCheckGeneric, package.DisplayName, e.Message), + []); } } else @@ -194,8 +188,8 @@ public async Task> GetLatestVersionAsync( return CheckUpdateResult.CreateFailure( package, InstallerErrorCode.UnsupportedRequest, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_PackageNotSupported, package.DisplayName, Factory.Name), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_PackageNotSupported, package.DisplayName, Factory.Name), + []); } })).ConfigureAwait(false); } @@ -210,8 +204,8 @@ public async Task InstallAsync(InstallRequest installRequest, IMa return InstallResult.CreateFailure( installRequest, InstallerErrorCode.UnsupportedRequest, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_PackageNotSupported, installRequest.DisplayName, Factory.Name), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_PackageNotSupported, installRequest.DisplayName, Factory.Name), + []); } try @@ -224,7 +218,7 @@ public async Task InstallAsync(InstallRequest installRequest, IMa } else { - string[] additionalNuGetSources = Array.Empty(); + string[] additionalNuGetSources = []; if (installRequest.Details != null && installRequest.Details.TryGetValue(InstallerConstants.NuGetSourcesKey, out string nugetSources)) { additionalNuGetSources = nugetSources.Split(InstallerConstants.NuGetSourcesSeparator); @@ -266,8 +260,8 @@ public async Task InstallAsync(InstallRequest installRequest, IMa return InstallResult.CreateFailure( installRequest, InstallerErrorCode.DownloadFailed, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_DownloadFailed, installRequest.DisplayName, packageLocation), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_DownloadFailed, installRequest.DisplayName, packageLocation), + []); } catch (PackageNotFoundException e) { @@ -275,27 +269,27 @@ public async Task InstallAsync(InstallRequest installRequest, IMa installRequest, InstallerErrorCode.PackageNotFound, string.Format(LocalizableStrings.NuGetInstaller_Error_FailedToReadPackage, e.PackageIdentifier, string.Join(", ", e.SourcesList)), - Array.Empty()); + []); } catch (InvalidNuGetSourceException e) { string message = e.SourcesList == null || !e.SourcesList.Any() - ? LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources_None - : string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidSources, string.Join(", ", e.SourcesList)); + ? LocalizableStrings.NuGetInstaller_InstallResult_Error_InvalidSources_None + : string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_InvalidSources, string.Join(", ", e.SourcesList)); return InstallResult.CreateFailure( installRequest, InstallerErrorCode.InvalidSource, message, - Array.Empty()); + []); } catch (InvalidNuGetPackageException e) { return InstallResult.CreateFailure( installRequest, InstallerErrorCode.InvalidPackage, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_InvalidPackage, e.PackageLocation), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_InvalidPackage, e.PackageLocation), + []); } catch (VulnerablePackageException e) { @@ -310,8 +304,8 @@ public async Task InstallAsync(InstallRequest installRequest, IMa return InstallResult.CreateFailure( installRequest, InstallerErrorCode.GenericError, - LocalizableStrings.NuGetInstaller_InstallResut_Error_OperationCancelled, - Array.Empty()); + LocalizableStrings.NuGetInstaller_InstallResult_Error_OperationCancelled, + []); } catch (Exception e) { @@ -319,8 +313,8 @@ public async Task InstallAsync(InstallRequest installRequest, IMa return InstallResult.CreateFailure( installRequest, InstallerErrorCode.GenericError, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_InstallGeneric, installRequest.DisplayName, e.Message), - Array.Empty()); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_InstallGeneric, installRequest.DisplayName, e.Message), + []); } } @@ -345,7 +339,7 @@ public Task UninstallAsync(IManagedTemplatePackage templatePack return Task.FromResult(UninstallResult.CreateFailure( templatePackage, InstallerErrorCode.UnsupportedRequest, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_PackageNotSupported, templatePackage.DisplayName, Factory.Name))); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_PackageNotSupported, templatePackage.DisplayName, Factory.Name))); } try { @@ -358,7 +352,7 @@ public Task UninstallAsync(IManagedTemplatePackage templatePack return Task.FromResult(UninstallResult.CreateFailure( templatePackage, InstallerErrorCode.GenericError, - string.Format(LocalizableStrings.NuGetInstaller_InstallResut_Error_UninstallGeneric, templatePackage.DisplayName, e.Message))); + string.Format(LocalizableStrings.NuGetInstaller_InstallResult_Error_UninstallGeneric, templatePackage.DisplayName, e.Message))); } } @@ -380,7 +374,7 @@ public async Task UpdateAsync(UpdateRequest updateRequest, IManage { throw new InvalidOperationException($"{nameof(uninstallResult.ErrorMessage)} cannot be null when {nameof(uninstallResult.Success)} is 'true'"); } - return UpdateResult.CreateFailure(updateRequest, uninstallResult.Error, uninstallResult.ErrorMessage, Array.Empty()); + return UpdateResult.CreateFailure(updateRequest, uninstallResult.Error, uninstallResult.ErrorMessage, []); } Dictionary installationDetails = new Dictionary(); @@ -449,7 +443,7 @@ private NuGetPackageInfo ReadPackageInformation(string packageLocation) null, nuspec.GetId(), nuspec.GetVersion().ToNormalizedString(), - Array.Empty()); + []); } } } diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstallerFactory.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstallerFactory.cs index c2926948c48..41fa55fc8b1 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstallerFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetInstallerFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetLogger.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetLogger.cs index 38fac85a307..e94062cf1dd 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetLogger.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetLogger.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NuGet.Common; using INuGetLogger = global::NuGet.Common.ILogger; diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetManagedTemplatePackage.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetManagedTemplatePackage.cs index 72a1bbca8d5..41fc7a55675 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetManagedTemplatePackage.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NuGetManagedTemplatePackage.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; diff --git a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NugetApiPackageManager.cs b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NugetApiPackageManager.cs index 21907d47690..5b267cfd188 100644 --- a/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NugetApiPackageManager.cs +++ b/src/Microsoft.TemplateEngine.Edge/Installers/NuGet/NugetApiPackageManager.cs @@ -1,13 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; using NuGet.Configuration; @@ -62,7 +56,7 @@ public async Task DownloadPackageAsync(string downloadPath, st throw new ArgumentException($"{nameof(downloadPath)} cannot be null or empty", nameof(downloadPath)); } - IEnumerable packagesSources = LoadNuGetSources(additionalSources?.ToArray() ?? Array.Empty()); + IEnumerable packagesSources = LoadNuGetSources(additionalSources?.ToArray() ?? []); if (!force) { @@ -211,7 +205,7 @@ await GetLatestVersionInternalAsync( FloatRange floatRange = new FloatRange(previewVersionInstalled ? NuGetVersionFloatBehavior.AbsoluteLatest : NuGetVersionFloatBehavior.Major); - string[] additionalSources = string.IsNullOrWhiteSpace(additionalSource) ? Array.Empty() : new[] { additionalSource! }; + string[] additionalSources = string.IsNullOrWhiteSpace(additionalSource) ? [] : new[] { additionalSource! }; IEnumerable packageSources = LoadNuGetSources(additionalSources); var (_, package) = await GetLatestVersionInternalAsync(identifier, packageSources, floatRange, cancellationToken).ConfigureAwait(false); bool isLatestVersion = currentVersion != null && currentVersion >= package.Identity.Version; @@ -338,7 +332,7 @@ await Task.WhenAll( continue; } atLeastOneSourceValid = true; - NugetPackageMetadata matchedVersion = foundPackages.FirstOrDefault(package => package.Identity.Version == packageVersion); + NugetPackageMetadata? matchedVersion = foundPackages.FirstOrDefault(package => package.Identity.Version == packageVersion); if (matchedVersion != null) { _nugetLogger.LogDebug($"{packageIdentifier}::{packageVersion} was found in {foundSource.Source}."); @@ -523,7 +517,7 @@ private IReadOnlyList ConvertVulnerabilityMetadata(IEnumerabl { if (vulnerabilities is null) { - return Array.Empty(); + return []; } return vulnerabilities.GroupBy(x => x.Severity) diff --git a/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.Designer.cs b/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.Designer.cs deleted file mode 100644 index 0592bb06def..00000000000 --- a/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,931 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Edge { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Edge.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Parameter conditions contain cyclic dependency: [{0}] that is preventing deterministic evaluation.. - /// - internal static string ConditionEvaluation_Error_CyclicDependency { - get { - return ResourceManager.GetString("ConditionEvaluation_Error_CyclicDependency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to evaluate condition {0} on parameter {1} (condition text: {2}, evaluation error: {3}) - condition might be malformed or referenced parameters do not have default nor explicit values.. - /// - internal static string ConditionEvaluation_Error_MismatchedCondition { - get { - return ResourceManager.GetString("ConditionEvaluation_Error_MismatchedCondition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unexpected internal error - unable to perform topological sort of parameter dependencies that do not appear to have a cyclic dependencies.. - /// - internal static string ConditionEvaluation_Error_TopologicalSort { - get { - return ResourceManager.GetString("ConditionEvaluation_Error_TopologicalSort", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Parameter conditions contain cyclic dependency: [{0}]. With current values of parameters it's possible to deterministically evaluate parameters - so proceeding further. However template should be reviewed as instantiation with different parameters can lead to error.. - /// - internal static string ConditionEvaluation_Warning_CyclicDependency { - get { - return ResourceManager.GetString("ConditionEvaluation_Warning_CyclicDependency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' should not contain empty items. - /// - internal static string Constaint_Error_ArgumentHasEmptyString { - get { - return ResourceManager.GetString("Constaint_Error_ArgumentHasEmptyString", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Argument(s) were not specified. At least one argument should be specified.. - /// - internal static string Constraint_Error_ArgumentsNotSpecified { - get { - return ResourceManager.GetString("Constraint_Error_ArgumentsNotSpecified", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' does not contain valid items.. - /// - internal static string Constraint_Error_ArrayHasNoObjects { - get { - return ResourceManager.GetString("Constraint_Error_ArrayHasNoObjects", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid JSON.. - /// - internal static string Constraint_Error_InvalidJson { - get { - return ResourceManager.GetString("Constraint_Error_InvalidJson", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' should be an array of objects.. - /// - internal static string Constraint_Error_InvalidJsonArray_Objects { - get { - return ResourceManager.GetString("Constraint_Error_InvalidJsonArray_Objects", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid JSON array.. - /// - internal static string Constraint_Error_InvalidJsonType_Array { - get { - return ResourceManager.GetString("Constraint_Error_InvalidJsonType_Array", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid JSON string or array.. - /// - internal static string Constraint_Error_InvalidJsonType_StringOrArray { - get { - return ResourceManager.GetString("Constraint_Error_InvalidJsonType_StringOrArray", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid version or version range.. - /// - internal static string Constraint_Error_InvalidVersion { - get { - return ResourceManager.GetString("Constraint_Error_InvalidVersion", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Check the constraint configuration in template.json.. - /// - internal static string Constraint_WrongConfigurationCTA { - get { - return ResourceManager.GetString("Constraint_WrongConfigurationCTA", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Environment variables. - /// - internal static string EnvironmentVariablesBindSource_Name { - get { - return ResourceManager.GetString("EnvironmentVariablesBindSource_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Attempt to pass result of external evaluation of parameters conditions for parameter(s) that do not have appropriate condition set in template (IsEnabled or IsRequired attributes not populated with condition) or a failure to pass the condition results for parameters with condition(s) in template. Offending parameters: {0}.. - /// - internal static string EvaluatedInputDataSet_Error_MismatchedConditions { - get { - return ResourceManager.GetString("EvaluatedInputDataSet_Error_MismatchedConditions", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Attempt to pass result of external evaluation of parameters conditions for parameter(s) that do not have appropriate condition set in template (IsEnabled or IsRequired attributes not populated with condition) or a failure to pass the condition results for parameters with condition(s) in template. Offending parameter(s): {0}.. - /// - internal static string EvaluatedInputParameterData_Error_ConditionsInvalid { - get { - return ResourceManager.GetString("EvaluatedInputParameterData_Error_ConditionsInvalid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The folder {0} doesn't exist.. - /// - internal static string FolderInstaller_InstallResult_Error_FolderDoesNotExist { - get { - return ResourceManager.GetString("FolderInstaller_InstallResult_Error_FolderDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Check the constraint configuration in template.json.. - /// - internal static string Generic_Constraint_WrongConfigurationCTA { - get { - return ResourceManager.GetString("Generic_Constraint_WrongConfigurationCTA", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to latest version. - /// - internal static string Generic_LatestVersion { - get { - return ResourceManager.GetString("Generic_LatestVersion", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to version {0}. - /// - internal static string Generic_Version { - get { - return ResourceManager.GetString("Generic_Version", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to read installed template packages list at {0}. It might be due to the file is corrupted. Please review this file manually and fix the errors in JSON structure, or remove the file to clear up the list of list installed packages and reinstall them again. Details of the error: {1}.. - /// - internal static string GlobalSettings_Error_CorruptedSettings { - get { - return ResourceManager.GetString("GlobalSettings_Error_CorruptedSettings", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} can be installed by several installers. Specify the installer name to be used.. - /// - internal static string GlobalSettingsTemplatePackageProvider_InstallResult_Error_MultipleInstallersCanBeUsed { - get { - return ResourceManager.GetString("GlobalSettingsTemplatePackageProvider_InstallResult_Error_MultipleInstallersCanBe" + - "Used", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} is already installed.. - /// - internal static string GlobalSettingsTemplatePackageProvider_InstallResult_Error_PackageAlreadyInstalled { - get { - return ResourceManager.GetString("GlobalSettingsTemplatePackageProvider_InstallResult_Error_PackageAlreadyInstalled" + - "", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} cannot be installed.. - /// - internal static string GlobalSettingsTemplatePackageProvider_InstallResult_Error_PackageCannotBeInstalled { - get { - return ResourceManager.GetString("GlobalSettingsTemplatePackageProvider_InstallResult_Error_PackageCannotBeInstalle" + - "d", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} is already installed, it will be replaced with {1}.. - /// - internal static string GlobalSettingsTemplatePackagesProvider_Info_PackageAlreadyInstalled { - get { - return ResourceManager.GetString("GlobalSettingsTemplatePackagesProvider_Info_PackageAlreadyInstalled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} was successfully uninstalled.. - /// - internal static string GlobalSettingsTemplatePackagesProvider_Info_PackageUninstalled { - get { - return ResourceManager.GetString("GlobalSettingsTemplatePackagesProvider_Info_PackageUninstalled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' does not have mandatory property '{1}'.. - /// - internal static string HostConstraint_Error_MissingMandatoryProperty { - get { - return ResourceManager.GetString("HostConstraint_Error_MissingMandatoryProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running template on {0} (version: {1}) is not supported, supported hosts is/are: {2}.. - /// - internal static string HostConstraint_Message_Restricted { - get { - return ResourceManager.GetString("HostConstraint_Message_Restricted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template engine host. - /// - internal static string HostConstraint_Name { - get { - return ResourceManager.GetString("HostConstraint_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Host defined parameters. - /// - internal static string HostParametersBindSource_Name { - get { - return ResourceManager.GetString("HostParametersBindSource_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found package is vulnerable source: {0}. - /// - internal static string NuGetApiPackageManager_DownloadError_VulnerablePackage { - get { - return ResourceManager.GetString("NuGetApiPackageManager_DownloadError_VulnerablePackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load the NuGet source {0}.. - /// - internal static string NuGetApiPackageManager_Error_FailedToLoadSource { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Error_FailedToLoadSource", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load NuGet sources configured for the folder {0}.. - /// - internal static string NuGetApiPackageManager_Error_FailedToLoadSources { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Error_FailedToLoadSources", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to read package information from NuGet source {0}.. - /// - internal static string NuGetApiPackageManager_Error_FailedToReadPackage { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Error_FailedToReadPackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File {0} already exists.. - /// - internal static string NuGetApiPackageManager_Error_FileAlreadyExists { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Error_FileAlreadyExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No NuGet sources are defined or enabled.. - /// - internal static string NuGetApiPackageManager_Error_NoSources { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Error_NoSources", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The checked package {0} is vulnerable.. - /// - internal static string NuGetApiPackageManager_UpdateCheckError_VulnerablePackage { - get { - return ResourceManager.GetString("NuGetApiPackageManager_UpdateCheckError_VulnerablePackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to remove {0} after failed download. Remove the file manually if it exists.. - /// - internal static string NuGetApiPackageManager_Warning_FailedToDelete { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Warning_FailedToDelete", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to download {0} from NuGet feed {1}.. - /// - internal static string NuGetApiPackageManager_Warning_FailedToDownload { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Warning_FailedToDownload", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load NuGet source {0}: the source is not valid. It will be skipped in further processing.. - /// - internal static string NuGetApiPackageManager_Warning_FailedToLoadSource { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Warning_FailedToLoadSource", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The NuGet sources {0} are insecure and will not be searched. If you want to include those sources for search, use --force.. - /// - internal static string NuGetApiPackageManager_Warning_InsecureFeed { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Warning_InsecureFeed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} is not found in NuGet feeds {1}.. - /// - internal static string NuGetApiPackageManager_Warning_PackageNotFound { - get { - return ResourceManager.GetString("NuGetApiPackageManager_Warning_PackageNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to copy package {0} to {1}.. - /// - internal static string NuGetInstaller_Error_CopyFailed { - get { - return ResourceManager.GetString("NuGetInstaller_Error_CopyFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to read content of package {0}.. - /// - internal static string NuGetInstaller_Error_FailedToReadPackage { - get { - return ResourceManager.GetString("NuGetInstaller_Error_FailedToReadPackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File {0} already exists.. - /// - internal static string NuGetInstaller_Error_FileAlreadyExists { - get { - return ResourceManager.GetString("NuGetInstaller_Error_FileAlreadyExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The requested package {0} has vulnerabilities.. - /// - internal static string NuGetInstaller_InstallResult_Error_VulnerablePackage { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResult_Error_VulnerablePackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to download {0} from {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_DownloadFailed { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_DownloadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to install the package {0}. - ///Details: {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_InstallGeneric { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_InstallGeneric", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The install request {0} cannot be processed by installer {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_InstallRequestNotSupported { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_InstallRequestNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The NuGet package {0} is invalid.. - /// - internal static string NuGetInstaller_InstallResut_Error_InvalidPackage { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_InvalidPackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The configured NuGet sources are invalid: {0}.. - /// - internal static string NuGetInstaller_InstallResut_Error_InvalidSources { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_InvalidSources", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No NuGet sources are configured.. - /// - internal static string NuGetInstaller_InstallResut_Error_InvalidSources_None { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_InvalidSources_None", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The operation was cancelled.. - /// - internal static string NuGetInstaller_InstallResut_Error_OperationCancelled { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_OperationCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} was not found in NuGet feeds {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_PackageNotFound { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_PackageNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The package {0} is not supported by installer {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_PackageNotSupported { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_PackageNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to uninstall the package {0}. - ///Details: {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_UninstallGeneric { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_UninstallGeneric", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to check the update for the package {0}. - ///Details: {1}.. - /// - internal static string NuGetInstaller_InstallResut_Error_UpdateCheckGeneric { - get { - return ResourceManager.GetString("NuGetInstaller_InstallResut_Error_UpdateCheckGeneric", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The checked package {0} has vulnerabilities.. - /// - internal static string NuGetInstaller_UpdateCheck_Error_VulnerablePackage { - get { - return ResourceManager.GetString("NuGetInstaller_UpdateCheck_Error_VulnerablePackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid operating system name. Allowed values are: {1}.. - /// - internal static string OSConstraint_Error_InvalidOSName { - get { - return ResourceManager.GetString("OSConstraint_Error_InvalidOSName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running template on {0} is not supported, supported OS is/are: {1}.. - /// - internal static string OSConstraint_Message_Restricted { - get { - return ResourceManager.GetString("OSConstraint_Message_Restricted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Operating System. - /// - internal static string OSConstraint_Name { - get { - return ResourceManager.GetString("OSConstraint_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template package location {0} is not supported, or doesn't exist.. - /// - internal static string Scanner_Error_TemplatePackageLocationIsNotSupported { - get { - return ResourceManager.GetString("Scanner_Error_TemplatePackageLocationIsNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' is not a valid semver version.. - /// - internal static string SdkConstraint_Error_InvalidVersion { - get { - return ResourceManager.GetString("SdkConstraint_Error_InvalidVersion", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Multiple 'ISdkInfoProvider' components provided by host ({0}), therefore 'SdkVersionConstraint' cannot be properly initialized.. - /// - internal static string SdkConstraint_Error_MismatchedProviders { - get { - return ResourceManager.GetString("SdkConstraint_Error_MismatchedProviders", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No 'ISdkInfoProvider' component provided by host. 'SdkVersionConstraint' cannot be properly initialized.. - /// - internal static string SdkConstraint_Error_MissingProvider { - get { - return ResourceManager.GetString("SdkConstraint_Error_MissingProvider", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running template on current .NET SDK version ({0}) is unsupported. Supported version(s): {1}. - /// - internal static string SdkConstraint_Message_Restricted { - get { - return ResourceManager.GetString("SdkConstraint_Message_Restricted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to .NET SDK version. - /// - internal static string SdkVersionConstraint_Name { - get { - return ResourceManager.GetString("SdkVersionConstraint_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The constraint '{0}' failed to be evaluated for the args '{1}', details: {2}. - /// - internal static string TemplateConstraintManager_Error_FailedToEvaluate { - get { - return ResourceManager.GetString("TemplateConstraintManager_Error_FailedToEvaluate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The constraint '{0}' failed to initialize: {1}. - /// - internal static string TemplateConstraintManager_Error_FailedToInitialize { - get { - return ResourceManager.GetString("TemplateConstraintManager_Error_FailedToInitialize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The constraint '{0}' is unknown.. - /// - internal static string TemplateConstraintManager_Error_UnknownType { - get { - return ResourceManager.GetString("TemplateConstraintManager_Error_UnknownType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Could not load template.. - /// - internal static string TemplateCreator_TemplateCreationResult_Error_CouldNotLoadTemplate { - get { - return ResourceManager.GetString("TemplateCreator_TemplateCreationResult_Error_CouldNotLoadTemplate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to create template. - ///Details: {0}. - /// - internal static string TemplateCreator_TemplateCreationResult_Error_CreationFailed { - get { - return ResourceManager.GetString("TemplateCreator_TemplateCreationResult_Error_CreationFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Destructive changes detected.. - /// - internal static string TemplateCreator_TemplateCreationResult_Error_DestructiveChanges { - get { - return ResourceManager.GetString("TemplateCreator_TemplateCreationResult_Error_DestructiveChanges", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template is invalid and cannot be instantiated.. - /// - internal static string TemplateCreator_TemplateCreationResult_Error_InvalidTemplate { - get { - return ResourceManager.GetString("TemplateCreator_TemplateCreationResult_Error_InvalidTemplate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to create template: the template name is not specified. Template configuration does not configure a default name that can be used when name is not specified. Specify the name for the template when instantiating or configure a default name in the template configuration.. - /// - internal static string TemplateCreator_TemplateCreationResult_Error_NoDefaultName { - get { - return ResourceManager.GetString("TemplateCreator_TemplateCreationResult_Error_NoDefaultName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load host data in {0} at {1}.. - /// - internal static string TemplateInfo_Warning_FailedToReadHostData { - get { - return ResourceManager.GetString("TemplateInfo_Warning_FailedToReadHostData", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to retrieve package with identifier '{0}'.. - /// - internal static string TemplatePackageManager_Error_FailedToFindPackage { - get { - return ResourceManager.GetString("TemplatePackageManager_Error_FailedToFindPackage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to retrieve template packages from provider '{0}'. - ///Details: {1}. - /// - internal static string TemplatePackageManager_Error_FailedToGetTemplatePackages { - get { - return ResourceManager.GetString("TemplatePackageManager_Error_FailedToGetTemplatePackages", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to scan {0}. - ///Details: {1}. - /// - internal static string TemplatePackageManager_Error_FailedToScan { - get { - return ResourceManager.GetString("TemplatePackageManager_Error_FailedToScan", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to store template cache, details: {0} - ///Template cache will be recreated on the next run.. - /// - internal static string TemplatePackageManager_Error_FailedToStoreCache { - get { - return ResourceManager.GetString("TemplatePackageManager_Error_FailedToStoreCache", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to - ///The following templates use the same identity '{0}': - ///{1} - ///The template from '{2}' will be used. To resolve this conflict, uninstall the conflicting template packages.. - /// - internal static string TemplatePackageManager_Warning_DetectedTemplatesIdentityConflict { - get { - return ResourceManager.GetString("TemplatePackageManager_Warning_DetectedTemplatesIdentityConflict", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} '{1}' from '{2}'. - /// - internal static string TemplatePackageManager_Warning_DetectedTemplatesIdentityConflict_Subentry { - get { - return ResourceManager.GetString("TemplatePackageManager_Warning_DetectedTemplatesIdentityConflict_Subentry", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation errors:. - /// - internal static string Validation_Error_Header { - get { - return ResourceManager.GetString("Validation_Error_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation messages:. - /// - internal static string Validation_Info_Header { - get { - return ResourceManager.GetString("Validation_Info_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load the template {0}: the template is not valid.. - /// - internal static string Validation_InvalidTemplate { - get { - return ResourceManager.GetString("Validation_InvalidTemplate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load the '{0}' localization the template {1}: the localization file is not valid. The localization will be skipped.. - /// - internal static string Validation_InvalidTemplateLoc { - get { - return ResourceManager.GetString("Validation_InvalidTemplateLoc", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation errors in '{1}' localization:. - /// - internal static string Validation_LocError_Header { - get { - return ResourceManager.GetString("Validation_LocError_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation messages in '{1}' localization:. - /// - internal static string Validation_LocInfo_Header { - get { - return ResourceManager.GetString("Validation_LocInfo_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation warnings in '{1}' localization:. - /// - internal static string Validation_LocWarning_Header { - get { - return ResourceManager.GetString("Validation_LocWarning_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template {0} has the following validation warnings:. - /// - internal static string Validation_Warning_Header { - get { - return ResourceManager.GetString("Validation_Warning_Header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Multiple 'IWorkloadsInfoProvider' components provided by host ({0}), therefore 'WorkloadConstraint' cannot be properly initialized.. - /// - internal static string WorkloadConstraint_Error_MismatchedProviders { - get { - return ResourceManager.GetString("WorkloadConstraint_Error_MismatchedProviders", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No 'IWorkloadsInfoProvider' component provided by host. 'WorkloadConstraint' cannot be properly initialized.. - /// - internal static string WorkloadConstraint_Error_MissingProvider { - get { - return ResourceManager.GetString("WorkloadConstraint_Error_MissingProvider", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Running template is not supported - required optional workload(s) not installed. Supported workload(s): {0}. Currently installed optional workloads: {1}. - /// - internal static string WorkloadConstraint_Message_Restricted { - get { - return ResourceManager.GetString("WorkloadConstraint_Message_Restricted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Workload. - /// - internal static string WorkloadConstraint_Name { - get { - return ResourceManager.GetString("WorkloadConstraint_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'IWorkloadsInfoProvider' component provided by host provided some duplicated workloads (duplicates: {0}). Duplicates will be skipped.. - /// - internal static string WorkloadConstraint_Warning_DuplicateWorkloads { - get { - return ResourceManager.GetString("WorkloadConstraint_Warning_DuplicateWorkloads", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.resx b/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.resx index 80678e6f6e5..3474d168dfa 100644 --- a/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.resx +++ b/src/Microsoft.TemplateEngine.Edge/LocalizableStrings.resx @@ -135,7 +135,7 @@ Parameter conditions contain cyclic dependency: [{0}]. With current values of parameters it's possible to deterministically evaluate parameters - so proceeding further. However template should be reviewed as instantiation with different parameters can lead to error. {0} is the dependency chain - + '{0}' should not contain empty items {0} is JSON configuration for constraint @@ -268,45 +268,45 @@ File {0} already exists. - + Failed to download {0} from {1}. - + Failed to install the package {0}. Details: {1}. - + The install request {0} cannot be processed by installer {1}. - + The NuGet package {0} is invalid. The requested package {0} has vulnerabilities. - + The configured NuGet sources are invalid: {0}. - + No NuGet sources are configured. - + The operation was cancelled. - + {0} was not found in NuGet feeds {1}. - + The package {0} is not supported by installer {1}. - + Failed to uninstall the package {0}. Details: {1}. The checked package {0} has vulnerabilities. - + Failed to check the update for the package {0}. Details: {1}. @@ -413,7 +413,7 @@ Details: {0} Details: {1} {0} - provider name (not localized). Last line should not end with a period - period is already included in {1}. - + Failed to retrieve package with identifier '{0}'. @@ -466,4 +466,4 @@ The template from 'PACKAGE_ID' will be used. To resolve this conflict, uninstall The template is invalid and cannot be instantiated. - + \ No newline at end of file diff --git a/src/Microsoft.TemplateEngine.Edge/Microsoft.TemplateEngine.Edge.csproj b/src/Microsoft.TemplateEngine.Edge/Microsoft.TemplateEngine.Edge.csproj index 3c58a55ae6a..4e2f31cc381 100644 --- a/src/Microsoft.TemplateEngine.Edge/Microsoft.TemplateEngine.Edge.csproj +++ b/src/Microsoft.TemplateEngine.Edge/Microsoft.TemplateEngine.Edge.csproj @@ -1,12 +1,17 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Helper package for adding Template Engine to consuming applications true true true - $(DefineConstants);NETFULL + + + + + + annotations @@ -23,24 +28,16 @@ - - - - - True - True - LocalizableStrings.resx - + + - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileDirectory.cs b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileDirectory.cs index 3df76a4aebd..df39da79788 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileDirectory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileDirectory.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text.RegularExpressions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileFile.cs b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileFile.cs index 5dbbbf259ae..556ef80b916 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileFile.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileFile.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.IO.Compression; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPoint.cs b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPoint.cs index 1d6e502a57b..6b0207d4769 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPoint.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPoint.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.IO.Compression; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -89,7 +87,7 @@ internal IReadOnlyDictionary Universe internal Guid MountPointFactoryId => ZipFileMountPointFactory.FactoryId; - public IFile? FileInfo(string path) + public IFile FileInfo(string path) { return new ZipFileFile(this, path, path.Substring(path.LastIndexOf('/') + 1), null); } diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPointFactory.cs b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPointFactory.cs index bfd7bf701e5..3b26df76071 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPointFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/Archive/ZipFileMountPointFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.IO.Compression; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/DirectoryBase.cs b/src/Microsoft.TemplateEngine.Edge/Mount/DirectoryBase.cs index 732a192297f..e9c7b014009 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/DirectoryBase.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/DirectoryBase.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Edge.Mount diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileBase.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileBase.cs index eb66d37e516..32600522ebb 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileBase.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Edge.Mount diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemDirectory.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemDirectory.cs index 141a195125d..75fbb6eddda 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemDirectory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemDirectory.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; using Microsoft.TemplateEngine.Edge.Settings; diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemFile.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemFile.cs index a114cafe588..d89bf84c4d4 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemFile.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemFile.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Edge.Mount.FileSystem diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPoint.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPoint.cs index 671a3a254f1..65074964d09 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPoint.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPoint.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Edge.Settings; @@ -40,7 +38,7 @@ internal FileSystemMountPoint(IEngineEnvironmentSettings environmentSettings, st ///
internal string MountPointRootPath { get; } - public IFile? FileInfo(string path) + public IFile FileInfo(string path) { string fullPath = Path.Combine(MountPointRootPath, path.TrimStart('/')); diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPointFactory.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPointFactory.cs index 09e766a8dc9..2ecf2acca57 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPointFactory.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystem/FileSystemMountPointFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystemInfoBase.cs b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystemInfoBase.cs index 99c3bfdda40..b7132a16a94 100644 --- a/src/Microsoft.TemplateEngine.Edge/Mount/FileSystemInfoBase.cs +++ b/src/Microsoft.TemplateEngine.Edge/Mount/FileSystemInfoBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Edge.Mount diff --git a/src/Microsoft.TemplateEngine.Edge/PublicAPI.Shipped.txt b/src/Microsoft.TemplateEngine.Edge/PublicAPI.Shipped.txt index bb4433c540f..276f69f40ba 100644 --- a/src/Microsoft.TemplateEngine.Edge/PublicAPI.Shipped.txt +++ b/src/Microsoft.TemplateEngine.Edge/PublicAPI.Shipped.txt @@ -267,3 +267,4 @@ static Microsoft.TemplateEngine.Edge.Template.InputDataStateUtil.GetInputDataSta static Microsoft.TemplateEngine.Edge.Template.TemplateEqualityComparer.Default.get -> System.Collections.Generic.IEqualityComparer! static Microsoft.TemplateEngine.Edge.Template.TemplateMatchInfoEqualityComparer.Default.get -> System.Collections.Generic.IEqualityComparer! ~Microsoft.TemplateEngine.Edge.FilterableTemplateInfo.ParameterDefinitions.get -> Microsoft.TemplateEngine.Abstractions.Parameters.IParameterDefinitionSet +Microsoft.TemplateEngine.Edge.DefaultTemplateEngineHost.WorkingDirectory.get -> string! \ No newline at end of file diff --git a/src/Microsoft.TemplateEngine.Edge/PublicAPI.Unshipped.txt b/src/Microsoft.TemplateEngine.Edge/PublicAPI.Unshipped.txt index 37f0acddcd0..6d200233a55 100644 --- a/src/Microsoft.TemplateEngine.Edge/PublicAPI.Unshipped.txt +++ b/src/Microsoft.TemplateEngine.Edge/PublicAPI.Unshipped.txt @@ -5,6 +5,6 @@ Microsoft.TemplateEngine.Edge.Settings.ScanResult.Templates.get -> System.Collec Microsoft.TemplateEngine.Edge.Settings.ITemplateInfoHostJsonCache.HostData.get -> string? Microsoft.TemplateEngine.Edge.Settings.TemplatePackageManager.GetManagedTemplatePackageAsync(string! packageIdentifier, string? packageVersion = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<(Microsoft.TemplateEngine.Abstractions.TemplatePackage.IManagedTemplatePackage? Package, System.Collections.Generic.IEnumerable? Templates)>! Microsoft.TemplateEngine.Edge.VirtualEnvironment -Microsoft.TemplateEngine.Edge.VirtualEnvironment.VirtualEnvironment(System.Collections.Generic.IReadOnlyDictionary? virtualEnvironemnt, bool includeRealEnvironment) -> void +Microsoft.TemplateEngine.Edge.VirtualEnvironment.VirtualEnvironment(System.Collections.Generic.IReadOnlyDictionary? virtualEnvironment, bool includeRealEnvironment) -> void static Microsoft.TemplateEngine.Edge.DefaultEnvironment.FetchEnvironmentVariables() -> System.Collections.Generic.IReadOnlyDictionary! Microsoft.TemplateEngine.Edge.FilterableTemplateInfo.PreferDefaultName.get -> bool \ No newline at end of file diff --git a/src/Microsoft.TemplateEngine.Edge/ReflectionLoadProbingPath.cs b/src/Microsoft.TemplateEngine.Edge/ReflectionLoadProbingPath.cs index 2989e293647..75806ba5e79 100644 --- a/src/Microsoft.TemplateEngine.Edge/ReflectionLoadProbingPath.cs +++ b/src/Microsoft.TemplateEngine.Edge/ReflectionLoadProbingPath.cs @@ -1,17 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; - -#if !NETFULL - +#if NET using System.Runtime.Loader; - #endif namespace Microsoft.TemplateEngine.Edge @@ -32,7 +25,7 @@ private ReflectionLoadProbingPath(string path) internal static void Add(string basePath) { Instance.Add(new ReflectionLoadProbingPath(basePath)); -#if !NETFULL +#if NET AssemblyLoadContext.Default.Resolving += Resolving; #else AppDomain.CurrentDomain.AssemblyResolve += Resolving; @@ -49,8 +42,7 @@ internal static void Reset() Instance.Clear(); } -#if !NETFULL - +#if NET private static Assembly? SelectBestMatch(AssemblyLoadContext loadContext, AssemblyName match, IEnumerable candidates) #else private static Assembly? SelectBestMatch(object sender, AssemblyName match, IEnumerable candidates) @@ -73,7 +65,7 @@ internal static void Reset() continue; } -#if !NETFULL +#if NET AssemblyName candidateName = AssemblyLoadContext.GetAssemblyName(file.FullName); #else AssemblyName candidateName = AssemblyName.GetAssemblyName(file.FullName); @@ -186,7 +178,7 @@ internal static void Reset() try { string attempt = bestMatch.Pop(); -#if !NETFULL +#if NET Assembly result = loadContext.LoadFromAssemblyPath(attempt); #else Assembly result = Assembly.LoadFile(attempt); @@ -202,14 +194,13 @@ internal static void Reset() }); } -#if !NETFULL - +#if NET private static Assembly? Resolving(AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName) #else private static Assembly? Resolving(object sender, ResolveEventArgs resolveEventArgs) #endif { -#if !NETFULL +#if NET string stringName = assemblyName.Name; #else string stringName = resolveEventArgs.Name; @@ -228,7 +219,7 @@ internal static void Reset() && (x.FullName.IndexOf($"{Path.DirectorySeparatorChar}netstandard", StringComparison.OrdinalIgnoreCase) > -1 || x.FullName.IndexOf($"{Path.DirectorySeparatorChar}netcoreapp", StringComparison.OrdinalIgnoreCase) > -1)) .OrderByDescending(x => x.FullName); -#if !NETFULL +#if NET found = SelectBestMatch(assemblyLoadContext, assemblyName, files); #else found = SelectBestMatch(sender, assemblyName, files); @@ -238,7 +229,7 @@ internal static void Reset() { FileInfo f = new FileInfo(Path.Combine(selector._path, stringName + ".dll")); FileInfo[] files = { f }; -#if !NETFULL +#if NET found = SelectBestMatch(assemblyLoadContext, assemblyName, files); #else found = SelectBestMatch(sender, assemblyName, files); @@ -249,7 +240,7 @@ internal static void Reset() { foreach (AssemblyName reference in found.GetReferencedAssemblies()) { -#if !NETFULL +#if NET Resolving(assemblyLoadContext, reference); #else ResolveEventArgs referenceArgs = new ResolveEventArgs(reference.FullName, found); diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/AsyncMutex.cs b/src/Microsoft.TemplateEngine.Edge/Settings/AsyncMutex.cs index b976ca3c8c7..8ddd7946d61 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/AsyncMutex.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/AsyncMutex.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.Edge.Settings { /// diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/ComponentManager.cs b/src/Microsoft.TemplateEngine.Edge/Settings/ComponentManager.cs index 0ff6f9e56ca..0802c5a2194 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/ComponentManager.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/ComponentManager.cs @@ -1,14 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; -#if !NETFULL +#if NET using System.Runtime.Loader; #endif @@ -76,10 +71,11 @@ public IEnumerable OfType() } else { - yield break; + return []; } } + var components = new List(); foreach (Guid id in ids) { if (TryGetComponent(id, out T? component)) @@ -88,9 +84,12 @@ public IEnumerable OfType() { throw new InvalidOperationException($"{nameof(component)} cannot be null when {nameof(TryGetComponent)} is 'true'"); } - yield return component; + + components.Add(component); } } + + return components; } } @@ -176,12 +175,12 @@ internal void AddProbingPath(string probeIn) // This method does not save the settings, it just registers into the memory cache. private bool RegisterType(Type type) { - if (!typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(type) || type.GetTypeInfo().GetConstructor(Type.EmptyTypes) == null || !type.GetTypeInfo().IsClass) + if (!typeof(IIdentifiedComponent).IsAssignableFrom(type) || type.GetConstructor(Type.EmptyTypes) == null || !type.IsClass) { return false; } - IReadOnlyList interfaceTypesToRegisterFor = type.GetTypeInfo().ImplementedInterfaces.Where(x => x != typeof(IIdentifiedComponent) && typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(x)).ToList(); + IReadOnlyList interfaceTypesToRegisterFor = type.GetInterfaces().Where(x => x != typeof(IIdentifiedComponent) && typeof(IIdentifiedComponent).IsAssignableFrom(x)).ToList(); if (interfaceTypesToRegisterFor.Count == 0) { return false; @@ -254,7 +253,7 @@ internal void Save() public void AddComponent(Type type, IIdentifiedComponent component) #pragma warning restore SA1202 // Elements should be ordered by access { - if (!type.IsAssignableFrom(component.GetType())) + if (!type.IsInstanceOfType(component)) { throw new ArgumentException($"{component.GetType().Name} should be assignable from {type.Name} type", nameof(type)); } @@ -287,7 +286,7 @@ private Type GetType(string typeName) if (!ReflectionLoadProbingPath.HasLoaded(asmName)) { AssemblyName name = new AssemblyName(asmName); -#if !NETFULL +#if NET AssemblyLoadContext.Default.LoadFromAssemblyName(name); #else AppDomain.CurrentDomain.Load(name); diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/FilteredTemplateInfo.cs b/src/Microsoft.TemplateEngine.Edge/Settings/FilteredTemplateInfo.cs index 093a464d1cc..b5195b2d6e4 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/FilteredTemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/FilteredTemplateInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge.Template; diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/LocalizationCacheKeyComparer.cs b/src/Microsoft.TemplateEngine.Edge/Settings/LocalizationCacheKeyComparer.cs index 8ca411bc0a3..680033a2763 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/LocalizationCacheKeyComparer.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/LocalizationCacheKeyComparer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Settings { /// diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/ScanResult.cs b/src/Microsoft.TemplateEngine.Edge/Settings/ScanResult.cs index c31b1b32992..d0267cb02d0 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/ScanResult.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/ScanResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/Scanner.cs b/src/Microsoft.TemplateEngine.Edge/Settings/Scanner.cs index a85e5d1e9d5..1147b4b578d 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/Scanner.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/Scanner.cs @@ -1,14 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; -using System.Threading; -using System.Threading.Tasks; -#if !NETFULL +#if NET using System.Runtime.Loader; #endif using Microsoft.Extensions.Logging; @@ -110,7 +104,7 @@ public Task ScanAsync( private MountPointScanSource GetOrCreateMountPointScanInfoForInstallSource(string sourceLocation) { - foreach (IMountPointFactory factory in _environmentSettings.Components.OfType().ToList()) + foreach (IMountPointFactory factory in _environmentSettings.Components.OfType()) { if (factory.TryMount(_environmentSettings, null, sourceLocation, out IMountPoint? mountPoint)) { @@ -253,7 +247,7 @@ private async Task ScanMountPointForTemplatesAsync( //backward compatibility var localizationLocators = templates.SelectMany(t => t.Localizations.Values.Where(li => li.IsValid || returnInvalidTemplates)).ToList(); - return new ScanResult(source.MountPoint, templates, localizationLocators, Array.Empty<(string, Type, IIdentifiedComponent)>()); + return new ScanResult(source.MountPoint, templates, localizationLocators, []); } /// @@ -279,16 +273,14 @@ private IEnumerable> LoadAllFromPath( { Assembly? assembly = null; -#if !NETFULL - if (file.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) > -1 || file.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) > -1) +#if NET + if (file.IndexOf("netcoreapp", StringComparison.OrdinalIgnoreCase) > -1) { - using (Stream fileStream = _environmentSettings.Host.FileSystem.OpenRead(file)) - { - assembly = AssemblyLoadContext.Default.LoadFromStream(fileStream); - } + using Stream fileStream = _environmentSettings.Host.FileSystem.OpenRead(file); + assembly = AssemblyLoadContext.Default.LoadFromStream(fileStream); } #else - if (file.IndexOf("net4", StringComparison.OrdinalIgnoreCase) > -1) + if (file.IndexOf("netstandard", StringComparison.OrdinalIgnoreCase) > -1 || file.IndexOf("net4", StringComparison.OrdinalIgnoreCase) > -1) { byte[] fileBytes = _environmentSettings.Host.FileSystem.ReadAllBytes(file); assembly = Assembly.Load(fileBytes); @@ -330,8 +322,6 @@ public MountPointScanSource(string location, IMountPoint mountPoint, bool should public bool FoundComponents { get; set; } public bool FoundTemplates { get; set; } - - public bool AnythingFound => FoundTemplates || FoundComponents; } } } diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/SettingsFilePaths.cs b/src/Microsoft.TemplateEngine.Edge/Settings/SettingsFilePaths.cs index 185885c006d..3b8658b3358 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/SettingsFilePaths.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/SettingsFilePaths.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge.Settings diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/SettingsStore.cs b/src/Microsoft.TemplateEngine.Edge/Settings/SettingsStore.cs index 70bb67161ab..dd203f47cd8 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/SettingsStore.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/SettingsStore.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json; diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs index daf5a96b356..92462ca29f8 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateCache.cs @@ -1,11 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -75,28 +71,28 @@ public TemplateCache(IReadOnlyList allTemplatePackages, ScanRe PrintOverlappingIdentityWarning(logger, templateDeduplicationDictionary); } - public TemplateCache(JObject? contentJobject) + public TemplateCache(JObject? contentJObject) { - if (contentJobject != null && contentJobject.TryGetValue(nameof(Version), StringComparison.OrdinalIgnoreCase, out JToken? versionToken)) + if (contentJObject != null && contentJObject.TryGetValue(nameof(Version), StringComparison.OrdinalIgnoreCase, out JToken? versionToken)) { Version = versionToken.ToString(); } else { Version = null; - TemplateInfo = Array.Empty(); + TemplateInfo = []; MountPointsInfo = new Dictionary(); Locale = string.Empty; return; } - Locale = contentJobject.TryGetValue(nameof(Locale), StringComparison.OrdinalIgnoreCase, out JToken? localeToken) + Locale = contentJObject.TryGetValue(nameof(Locale), StringComparison.OrdinalIgnoreCase, out JToken? localeToken) ? localeToken.ToString() : string.Empty; var mountPointInfo = new Dictionary(); - if (contentJobject.TryGetValue(nameof(MountPointsInfo), StringComparison.OrdinalIgnoreCase, out JToken? mountPointInfoToken) && mountPointInfoToken is IDictionary dict) + if (contentJObject.TryGetValue(nameof(MountPointsInfo), StringComparison.OrdinalIgnoreCase, out JToken? mountPointInfoToken) && mountPointInfoToken is IDictionary dict) { foreach (var entry in dict) { @@ -108,7 +104,7 @@ public TemplateCache(JObject? contentJobject) List templateList = new List(); - if (contentJobject.TryGetValue(nameof(TemplateInfo), StringComparison.OrdinalIgnoreCase, out JToken? templateInfoToken) && templateInfoToken is JArray arr) + if (contentJObject.TryGetValue(nameof(TemplateInfo), StringComparison.OrdinalIgnoreCase, out JToken? templateInfoToken) && templateInfoToken is JArray arr) { foreach (JToken entry in arr) { @@ -178,7 +174,7 @@ private void PrintOverlappingIdentityWarning(ILogger logger, IDictionary 1 managed templates with overlapping identities var lastTemplate = identityToTemplates.Value.Last(); var managedTemplates = identityToTemplates.Value.Where(templateInto => templateInto.TemplatePackage is IManagedTemplatePackage).ToArray(); - if (lastTemplate.TemplatePackage is IManagedTemplatePackage managedPackage && managedTemplates.Length > 1) + if (lastTemplate.TemplatePackage is IManagedTemplatePackage && managedTemplates.Length > 1) { var templatesList = new StringBuilder(); foreach (var (templateName, packageId, _, _) in managedTemplates) diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfo.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfo.cs index 9107457fe12..5b728afde8f 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -237,10 +234,10 @@ IReadOnlyDictionary ITemplateInfo.CacheParameters public string? HostData { get; private set; } [JsonProperty] - public IReadOnlyList PostActions { get; private set; } = Array.Empty(); + public IReadOnlyList PostActions { get; private set; } = []; [JsonProperty] - public IReadOnlyList Constraints { get; private set; } = Array.Empty(); + public IReadOnlyList Constraints { get; private set; } = []; public static TemplateInfo FromJObject(JObject entry) { diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfoReader.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfoReader.cs index 65627ddd036..264fde02f44 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfoReader.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateInfoReader.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -23,7 +21,7 @@ internal static TemplateInfo FromJObject(JObject entry) string mountPointUri = entry.ToString(nameof(MountPointUri)) ?? throw new ArgumentException($"{nameof(entry)} doesn't have {nameof(MountPointUri)} property.", nameof(entry)); string configPlace = entry.ToString(nameof(ConfigPlace)) ?? throw new ArgumentException($"{nameof(entry)} doesn't have {nameof(ConfigPlace)} property.", nameof(entry)); JToken? shortNameToken = entry.Get(nameof(ShortNameList)); - IEnumerable shortNames = shortNameToken.JTokenStringOrArrayToCollection(Array.Empty()); + IEnumerable shortNames = shortNameToken.JTokenStringOrArrayToCollection([]); TemplateInfo info = new TemplateInfo(identity, name, shortNames, mountPointUri, configPlace) { @@ -78,9 +76,9 @@ internal static TemplateInfo FromJObject(JObject entry) List templateParameters = new List(); foreach (JToken item in parametersArray) { - if (item is JObject jobj) + if (item is JObject jObj) { - templateParameters.Add(ParameterFromJObject(jobj)); + templateParameters.Add(ParameterFromJObject(jObj)); } } info.ParameterDefinitions = new ParameterDefinitionSet(templateParameters); diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateMatchInfo.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateMatchInfo.cs index cbc560ca60d..eac7ad95904 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplateMatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplateMatchInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge.Template; @@ -12,9 +9,9 @@ namespace Microsoft.TemplateEngine.Edge.Settings [Obsolete("This implementation is deprecated, use " + nameof(TemplateMatchInfo) + " instead")] internal class TemplateMatchInfoEx : ITemplateMatchInfo { - private readonly IList _matchDisposition; + private readonly List _matchDisposition; - private readonly IList _dispositionOfDefaults; + private readonly List _dispositionOfDefaults; public TemplateMatchInfoEx(ITemplateInfo info, IReadOnlyList matchDispositions) : this(info) @@ -37,12 +34,12 @@ public TemplateMatchInfoEx(ITemplateInfo info) public ITemplateInfo Info { get; } - public IReadOnlyList MatchDisposition => _matchDisposition.ToList(); + public IReadOnlyList MatchDisposition => _matchDisposition; // Stores match info relative to default settings. // These don't have to match for the template to be a match, but they can be used to filter matches // in appropriate situations. - // For example, matching or non-matching on the default language should only be used as a final disambiguator. + // For example, matching or non-matching on the default language should only be used as a final disambiguation. // It shouldn't unconditionally disqualify a match. public IReadOnlyList DispositionOfDefaults => _dispositionOfDefaults.ToList(); diff --git a/src/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs b/src/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs index 3a69256329f..32a33a2f10f 100644 --- a/src/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs +++ b/src/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs @@ -1,13 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.TemplateFiltering; diff --git a/src/Microsoft.TemplateEngine.Edge/Template/CreationResultStatus.cs b/src/Microsoft.TemplateEngine.Edge/Template/CreationResultStatus.cs index 00b7db306f1..8717d8ab8a5 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/CreationResultStatus.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/CreationResultStatus.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Edge.Template { /// diff --git a/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs b/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs index 5f4c7ab6642..2789ed35a23 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs @@ -16,7 +16,7 @@ public class EvaluatedInputParameterData : InputParameterData /// Constructor for type, that allows specification of results of external evaluation of conditions. /// /// - /// A stringified value of parameter or null for explicit unset. It's possible to indicate missing of parameter on input via argument. + /// A string converted value of parameter or null for explicit unset. It's possible to indicate missing of parameter on input via argument. /// /// /// diff --git a/src/Microsoft.TemplateEngine.Edge/Template/FilteredTemplateEqualityComparer.cs b/src/Microsoft.TemplateEngine.Edge/Template/FilteredTemplateEqualityComparer.cs index f72b991348b..9e779339ab8 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/FilteredTemplateEqualityComparer.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/FilteredTemplateEqualityComparer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Template { [Obsolete("IFilteredTemplateInfo is obsolete")] @@ -21,4 +18,4 @@ public int GetHashCode(IFilteredTemplateInfo obj) return obj?.Info?.Identity?.GetHashCode() ?? 0; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.TemplateEngine.Edge/Template/IFilteredTemplateInfo.cs b/src/Microsoft.TemplateEngine.Edge/Template/IFilteredTemplateInfo.cs index 92baa330354..3d7c1b375d9 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/IFilteredTemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/IFilteredTemplateInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge.Template diff --git a/src/Microsoft.TemplateEngine.Edge/Template/IParameterSetBuilder.cs b/src/Microsoft.TemplateEngine.Edge/Template/IParameterSetBuilder.cs index d044601e8bb..05940b90b65 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/IParameterSetBuilder.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/IParameterSetBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; diff --git a/src/Microsoft.TemplateEngine.Edge/Template/ITemplateMatchInfo.cs b/src/Microsoft.TemplateEngine.Edge/Template/ITemplateMatchInfo.cs index d66f5af8fec..28c8af44d09 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/ITemplateMatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/ITemplateMatchInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge.Template diff --git a/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs b/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs index 0c480daa936..54faa0615a2 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs @@ -2,15 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; namespace Microsoft.TemplateEngine.Edge.Template; /// -/// Datamodel for passing data into the . +/// Data model for passing data into the . /// public class InputDataSet : IReadOnlyDictionary { @@ -29,7 +27,7 @@ public InputDataSet(IParameterDefinitionSet parameters, IReadOnlyList /// Creates new instance of the type. - /// To be used to convert legacy parameters dictionaries into this datamodel. + /// To be used to convert legacy parameters dictionaries into this data model. /// /// public InputDataSet(ITemplateInfo templateInfo) @@ -38,7 +36,7 @@ public InputDataSet(ITemplateInfo templateInfo) /// /// Creates new instance of the type. - /// To be used to convert legacy parameters dictionaries into this datamodel. + /// To be used to convert legacy parameters dictionaries into this data model. /// /// /// diff --git a/src/Microsoft.TemplateEngine.Edge/Template/InputDataSetExtensions.cs b/src/Microsoft.TemplateEngine.Edge/Template/InputDataSetExtensions.cs index efe3e6fa5c1..37b2e7f2ea5 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/InputDataSetExtensions.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/InputDataSetExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Edge/Template/MatchInfo.cs b/src/Microsoft.TemplateEngine.Edge/Template/MatchInfo.cs index 2a97315d2a5..4b6837e739f 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/MatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/MatchInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Runtime.InteropServices; namespace Microsoft.TemplateEngine.Edge.Template diff --git a/src/Microsoft.TemplateEngine.Edge/Template/MatchLocation.cs b/src/Microsoft.TemplateEngine.Edge/Template/MatchLocation.cs index 4a1a7a276ae..c649f4aa795 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/MatchLocation.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/MatchLocation.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Edge.Template { [Obsolete("use" + nameof(Microsoft.TemplateEngine.Abstractions.TemplateFiltering.MatchInfo.Name) + " instead")] diff --git a/src/Microsoft.TemplateEngine.Edge/Template/OrdinalIgnoreCaseMatchInfoComparer.cs b/src/Microsoft.TemplateEngine.Edge/Template/OrdinalIgnoreCaseMatchInfoComparer.cs index 982337f8301..9d7354303b7 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/OrdinalIgnoreCaseMatchInfoComparer.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/OrdinalIgnoreCaseMatchInfoComparer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Template { [Obsolete("This class is deprecated")] diff --git a/src/Microsoft.TemplateEngine.Edge/Template/ParameterSetBuilder.cs b/src/Microsoft.TemplateEngine.Edge/Template/ParameterSetBuilder.cs index 048104079f1..3d9d2f2c50d 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/ParameterSetBuilder.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/ParameterSetBuilder.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -252,7 +249,7 @@ private static void EvaluateEnablementConditions( // Get the transitive closure of parameters that need to be recalculated, based on the knowledge of params that IReadOnlyList disabledParameters = parameters.Where(p => p.IsEnabledConditionResult.HasValue && !p.IsEnabledConditionResult.Value).ToList(); DirectedGraph parametersToRecalculate = - parametersDependenciesGraph.GetSubGraphDependandOnVertices(disabledParameters, includeSeedVertices: false); + parametersDependenciesGraph.GetSubGraphDependentOnVertices(disabledParameters, includeSeedVertices: false); // Second traversal - for transitive dependencies of parameters that need to be disabled if (parametersToRecalculate.TryGetTopologicalSort(out IReadOnlyList orderedParameters)) @@ -349,9 +346,6 @@ private void EvaluateConditionalParameters(IGenerator generator, ILogger logger) private class EvalData { - private object? _value; - private DataSource _dataSource = DataSource.NoSource; - public EvalData(ITemplateParameter parameterDefinition) { ParameterDefinition = parameterDefinition; @@ -360,7 +354,7 @@ public EvalData(ITemplateParameter parameterDefinition) public EvalData(EvaluatedInputParameterData other) : this(other.ParameterDefinition, other.Value, other.IsEnabledConditionResult, other.IsRequiredConditionResult) { - this._dataSource = DataSource.NoSource; + this.DataSource = DataSource.NoSource; } private EvalData( @@ -370,7 +364,7 @@ private EvalData( bool? isRequiredConditionResult) { ParameterDefinition = parameterDefinition; - _value = value; + Value = value; IsEnabledConditionResult = isEnabledConditionResult; IsRequiredConditionResult = isRequiredConditionResult; } @@ -383,14 +377,14 @@ private EvalData( public bool? IsRequiredConditionResult { get; set; } - public DataSource DataSource => _dataSource; + public DataSource DataSource { get; private set; } = DataSource.NoSource; - public object? Value => _value; + public object? Value { get; private set; } public void SetValue(object? value, DataSource source) { - _value = value; - _dataSource = source; + Value = value; + DataSource = source; InputDataState = InputDataStateUtil.GetInputDataState(value); } @@ -401,7 +395,7 @@ public EvaluatedInputParameterData ToParameterData() return new EvaluatedInputParameterData( this.ParameterDefinition, this.Value, - _dataSource, + DataSource, this.IsEnabledConditionResult, this.IsRequiredConditionResult, InputDataState); @@ -409,10 +403,10 @@ public EvaluatedInputParameterData ToParameterData() public EvalData Clone() { - var ds = _dataSource; + var ds = DataSource; return new EvalData(ParameterDefinition, Value, IsEnabledConditionResult, IsRequiredConditionResult) { - _dataSource = ds + DataSource = ds }; } diff --git a/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreationResult.cs b/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreationResult.cs index 33747b814d7..8280c1e3327 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreationResult.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreationResult.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge.Template diff --git a/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs b/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs index 809daecf35e..005e8edcc79 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -157,7 +152,6 @@ public async Task InstantiateAsync( { _environmentSettings.Host.FileSystem.CreateDirectory(targetDir); } - IComponentManager componentManager = _environmentSettings.Components; // setup separate sets of parameters to be used for GetCreationEffects() and by CreateAsync(). if (!TryCreateParameterSet(template, realName!, inputParameters, out IParameterSetData? effectParams, out TemplateCreationResult? resultIfParameterCreationFailed)) @@ -359,7 +353,7 @@ private void ResolveUserParameters(ITemplate template, IParameterSetBuilder temp { if (!inputParameters.HasConditions()) { - paramsWithInvalidValues = Array.Empty(); + paramsWithInvalidValues = []; isExternalEvaluationInvalid = false; return parametersBuilder.Build(false, template.Generator, _logger); } @@ -377,7 +371,7 @@ private void ResolveUserParameters(ITemplate template, IParameterSetBuilder temp template.Generator, _logger, !inputParameters.ContinueOnMismatchedConditionsEvaluation, out paramsWithInvalidValues)) { _logger.LogInformation( - "Parameters conditions ('IsEnbaled', 'IsRequired') evaluation supplied by host didn't match validation against internal evaluation for following parameters: [{0}]. Host requested to continue in such case: {1}", + "Parameters conditions ('IsEnabled', 'IsRequired') evaluation supplied by host didn't match validation against internal evaluation for following parameters: [{0}]. Host requested to continue in such case: {1}", paramsWithInvalidValues.ToCsvString(), inputParameters.ContinueOnMismatchedConditionsEvaluation); diff --git a/src/Microsoft.TemplateEngine.Edge/Template/TemplateEqualityComparer.cs b/src/Microsoft.TemplateEngine.Edge/Template/TemplateEqualityComparer.cs index 5380441d811..2ff2e613e29 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/TemplateEqualityComparer.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/TemplateEqualityComparer.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Edge.Template diff --git a/src/Microsoft.TemplateEngine.Edge/Template/TemplateMatchInfoEqualityComparer.cs b/src/Microsoft.TemplateEngine.Edge/Template/TemplateMatchInfoEqualityComparer.cs index 4e7933f6c43..9ba3fcdd0c5 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/TemplateMatchInfoEqualityComparer.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/TemplateMatchInfoEqualityComparer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Edge.Template { [Obsolete("This class is deprecated.")] diff --git a/src/Microsoft.TemplateEngine.Edge/Template/WellKnownSearchFilters.cs b/src/Microsoft.TemplateEngine.Edge/Template/WellKnownSearchFilters.cs index d855647b7d5..5758a0b6fc0 100644 --- a/src/Microsoft.TemplateEngine.Edge/Template/WellKnownSearchFilters.cs +++ b/src/Microsoft.TemplateEngine.Edge/Template/WellKnownSearchFilters.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Edge/TemplateConstraintManager.cs b/src/Microsoft.TemplateEngine.Edge/TemplateConstraintManager.cs index 25e083f1f1c..6a8ada2e6ca 100644 --- a/src/Microsoft.TemplateEngine.Edge/TemplateConstraintManager.cs +++ b/src/Microsoft.TemplateEngine.Edge/TemplateConstraintManager.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; @@ -17,15 +12,13 @@ namespace Microsoft.TemplateEngine.Edge /// public class TemplateConstraintManager : IDisposable { - private readonly IEngineEnvironmentSettings _engineEnvironmentSettings; private readonly ILogger _logger; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly Dictionary> _templateConstrains = new Dictionary>(); public TemplateConstraintManager(IEngineEnvironmentSettings engineEnvironmentSettings) { - _engineEnvironmentSettings = engineEnvironmentSettings; - _logger = _engineEnvironmentSettings.Host.LoggerFactory.CreateLogger(); + _logger = engineEnvironmentSettings.Host.LoggerFactory.CreateLogger(); var constraintFactories = engineEnvironmentSettings.Components.OfType(); _logger.LogDebug($"Found {constraintFactories.Count()} constraints factories, initializing."); @@ -60,7 +53,7 @@ public async Task> GetConstraintsAsync(IEnume try { - _logger.LogDebug($"Waiting for {constraintsToInitialize.Count()} to be initialized initialized."); + _logger.LogDebug($"Waiting for {constraintsToInitialize.Count()} to be initialized."); await CancellableWhenAll(constraintsToInitialize.Select(c => c.Task), cancellationToken).ConfigureAwait(false); _logger.LogDebug($"{constraintsToInitialize.Count()} constraints were initialized."); return constraintsToInitialize.Select(c => c.Task.Result).ToList(); diff --git a/src/Microsoft.TemplateEngine.Edge/TemplateListFilter.cs b/src/Microsoft.TemplateEngine.Edge/TemplateListFilter.cs index 11bd58af12a..3c5f8b6f60a 100644 --- a/src/Microsoft.TemplateEngine.Edge/TemplateListFilter.cs +++ b/src/Microsoft.TemplateEngine.Edge/TemplateListFilter.cs @@ -1,13 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - -#if NETFULL -using System.Linq; -#endif - using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge.Settings; using Microsoft.TemplateEngine.Edge.Template; @@ -57,10 +50,10 @@ public static IReadOnlyCollection FilterTemplates(IReadOn } } -#if !NETFULL - return matchingTemplates; -#else +#if NETFRAMEWORK return matchingTemplates.ToList(); +#else + return matchingTemplates; #endif } @@ -101,10 +94,10 @@ public static IReadOnlyCollection GetTemplateMatchInfo(IRead } } -#if !NETFULL - return matchingTemplates; -#else +#if NETFRAMEWORK return matchingTemplates.ToList(); +#else + return matchingTemplates; #endif } @@ -134,10 +127,10 @@ public static IReadOnlyCollection GetTemplateMatchInfo(IRead } } -#if !NETFULL - return matchingTemplates; -#else +#if NETFRAMEWORK return matchingTemplates.ToList(); +#else + return matchingTemplates; #endif } diff --git a/src/Microsoft.TemplateEngine.Edge/ValidationUtils.cs b/src/Microsoft.TemplateEngine.Edge/ValidationUtils.cs index 0c77e1f84cf..d2528b8f127 100644 --- a/src/Microsoft.TemplateEngine.Edge/ValidationUtils.cs +++ b/src/Microsoft.TemplateEngine.Edge/ValidationUtils.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Edge/VirtualEnvironment.cs b/src/Microsoft.TemplateEngine.Edge/VirtualEnvironment.cs index 4b90d107f58..a908c0512d6 100644 --- a/src/Microsoft.TemplateEngine.Edge/VirtualEnvironment.cs +++ b/src/Microsoft.TemplateEngine.Edge/VirtualEnvironment.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; @@ -17,14 +15,14 @@ public class VirtualEnvironment : DefaultEnvironment /// /// Creates new instance of . /// - /// Variables to be considered as environment variables. They have precedence over physical environment variables. + /// Variables to be considered as environment variables. They have precedence over physical environment variables. /// If set to true - variables from are added. - public VirtualEnvironment(IReadOnlyDictionary? virtualEnvironemnt, bool includeRealEnvironment) - : base(MergeEnvironmentVariables(virtualEnvironemnt, includeRealEnvironment)) + public VirtualEnvironment(IReadOnlyDictionary? virtualEnvironment, bool includeRealEnvironment) + : base(MergeEnvironmentVariables(virtualEnvironment, includeRealEnvironment)) { } private static IReadOnlyDictionary MergeEnvironmentVariables( - IReadOnlyDictionary? virtualEnvironemnt, bool includeRealEnvironment) + IReadOnlyDictionary? virtualEnvironment, bool includeRealEnvironment) { Dictionary variables = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -33,9 +31,9 @@ private static IReadOnlyDictionary MergeEnvironmentVariables( variables.Merge(FetchEnvironmentVariables()); } - if (virtualEnvironemnt != null) + if (virtualEnvironment != null) { - variables.Merge(virtualEnvironemnt); + variables.Merge(virtualEnvironment); } return variables; diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.cs.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.cs.xlf index 24fa7b2f272..efde981a7ea 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.cs.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.cs.xlf @@ -25,7 +25,7 @@ Podmínky parametru obsahují cyklickou závislost: [{0}]. S aktuálními hodnotami parametrů je možné deterministicky vyhodnotit parametry, takže pokračujeme dále. Šablona by se ale měla zkontrolovat, protože vytvoření instance s různými parametry může vést k chybě. {0} is the dependency chain - + '{0}' should not contain empty items {0} nesmí obsahovat prázdné položky. {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Soubor {0} již existuje. - + Failed to download {0} from {1}. Nepovedlo se stáhnout soubor {0} ze zdroje {1}. - + Failed to install the package {0}. Details: {1}. Balíček {0} se nepovedlo nainstalovat. Podrobnosti: {1} - + The install request {0} cannot be processed by installer {1}. Instalační program {1} nemohl zpracovat požadavek na instalaci balíčku {0}. - + The NuGet package {0} is invalid. Balíček NuGet {0} je neplatný. - + The configured NuGet sources are invalid: {0}. Nakonfigurované zdroje NuGet jsou neplatné: {0}. - + No NuGet sources are configured. Nejsou nakonfigurované žádné zdroje NuGet. - + The operation was cancelled. Operace se zrušila. - + {0} was not found in NuGet feeds {1}. Balíček {0} se nenašel v informačních kanálech NuGet {1}. - + The package {0} is not supported by installer {1}. Instalační program {1} nepodporuje balíček {0}. - + Failed to uninstall the package {0}. Details: {1}. Balíček {0} se nepovedlo odinstalovat. Podrobnosti: {1} - + Failed to check the update for the package {0}. Details: {1}. U balíčku {0} se nepovedlo zkontrolovat aktualizace. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.de.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.de.xlf index 2a722301771..e93e5cae324 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.de.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.de.xlf @@ -25,7 +25,7 @@ Parameterbedingungen enthalten eine zyklische Abhängigkeit [{0}]. Mit aktuellen Werten von Parametern ist es möglich, Parameter deterministisch auszuwerten, fahren Sie also fort. Die Vorlage sollte jedoch überprüft werden, da die Instanziierung mit unterschiedlichen Parametern zu Fehlern führen kann. {0} is the dependency chain - + '{0}' should not contain empty items „{0}“ darf keine leeren Elemente enthalten. {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Die Datei \"{0}\" ist bereits vorhanden. - + Failed to download {0} from {1}. Fehler beim Herunterladen von \"{0}\" von \"{1}\". - + Failed to install the package {0}. Details: {1}. Fehler beim Installieren des Pakets \"{0}\". Details: {1}. - + The install request {0} cannot be processed by installer {1}. Die Installationsanforderung \"{0}\" kann vom Installer \"{1}\" nicht verarbeitet werden. - + The NuGet package {0} is invalid. Das NuGet-Paket \"{0}\" ist ungültig. - + The configured NuGet sources are invalid: {0}. Die konfigurierten NuGet-Quellen sind ungültig: {0}. - + No NuGet sources are configured. Es sind keine NuGet-Quellen konfiguriert. - + The operation was cancelled. Der Vorgang wurde abgebrochen. - + {0} was not found in NuGet feeds {1}. \"{0}\" wurde in NuGet-Feeds \"{1}\" nicht gefunden. - + The package {0} is not supported by installer {1}. Das Paket \"{0}\" wird vom Installer \"{1}\" nicht unterstützt. - + Failed to uninstall the package {0}. Details: {1}. Fehler beim Deinstallieren des Pakets \"{0}\". Details: {1}. - + Failed to check the update for the package {0}. Details: {1}. Fehler beim Überprüfen des Updates für das Paket \"{0}\". diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.es.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.es.xlf index 5f10a7bf128..6bf1b24dc97 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.es.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.es.xlf @@ -25,7 +25,7 @@ Las condiciones del parámetro contienen una dependencia cíclica: [{0}]. Con los valores actuales de los parámetros, es posible evaluar los parámetros de forma determinista, por lo que es posible continuar. Sin embargo, la plantilla debe revisarse porque la creación de una instancia con diferentes parámetros puede dar lugar a un error. {0} is the dependency chain - + '{0}' should not contain empty items '{0}' no debe contener elementos vacíos {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ El archivo {0} ya existe. - + Failed to download {0} from {1}. No se pudo descargar {0} desde {1}. - + Failed to install the package {0}. Details: {1}. No se pudo instalar el paquete {0}. Detalles: {1}. - + The install request {0} cannot be processed by installer {1}. El instalador {1} no puede procesar la solicitud de instalación {0}. - + The NuGet package {0} is invalid. El paquete NuGet {0} no es válido. - + The configured NuGet sources are invalid: {0}. Los orígenes de NuGet configurados no son válidos: {0}. - + No NuGet sources are configured. No hay ningún origen NuGet configurado. - + The operation was cancelled. Se canceló la operación. - + {0} was not found in NuGet feeds {1}. No se encontró {0} en las fuentes de NuGet {1}. - + The package {0} is not supported by installer {1}. El instalador {1} no admite el paquete {0}. - + Failed to uninstall the package {0}. Details: {1}. No se pudo desinstalar el paquete {0}. Detalles: {1}. - + Failed to check the update for the package {0}. Details: {1}. No se pudo comprobar la actualización del paquete {0}. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.fr.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.fr.xlf index 94ce5095562..969a2fd2053 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.fr.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.fr.xlf @@ -25,7 +25,7 @@ Les conditions de paramètre contiennent une dépendance cyclique : [{0}]. Avec les valeurs actuelles des paramètres, il est possible d'évaluer les paramètres de manière déterministe – donc aller plus loin. Cependant, le modèle doit être revu car l'instanciation avec des paramètres différents peut entraîner des erreurs. {0} is the dependency chain - + '{0}' should not contain empty items « {0} » ne doit pas contenir d’éléments vides {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Le fichier {0} existe déjà. - + Failed to download {0} from {1}. Échec du téléchargement de {0} à partir de {1}. - + Failed to install the package {0}. Details: {1}. Échec de l’installation du package {0}. Détails : {1}. - + The install request {0} cannot be processed by installer {1}. La demande d’installation {0} ne peut pas être traitée par le programme d’installation {1}. - + The NuGet package {0} is invalid. Le package NuGet {0} est non valide. - + The configured NuGet sources are invalid: {0}. Les sources NuGet configurées sont non valides : {0}. - + No NuGet sources are configured. Aucune source NuGet n’est configurée. - + The operation was cancelled. L'opération a été annulée. - + {0} was not found in NuGet feeds {1}. {0} est introuvable dans les flux NuGet {1}. - + The package {0} is not supported by installer {1}. Le package {0} n’est pas pris en charge par le programme d’installation {1}. - + Failed to uninstall the package {0}. Details: {1}. Échec de la désinstallation du package {0}. Détails : {1}. - + Failed to check the update for the package {0}. Details: {1}. Échec de la vérification de la mise à jour du package {0}. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.it.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.it.xlf index c55c3d26c37..5f3c46424ec 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.it.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.it.xlf @@ -25,7 +25,7 @@ Le condizioni dei parametri contengono una dipendenza ciclica: [{0}]. Con i valori correnti dei parametri è possibile valutare deterministicamente i parametri, quindi continuare. È tuttavia necessario verificare il modello perché la creazione di un'istanza con parametri diversi può causare errori. {0} is the dependency chain - + '{0}' should not contain empty items '{0}' non deve contenere elementi vuoti {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Il file {0} esiste già. - + Failed to download {0} from {1}. Non è stato possibile scaricare {0} da {1}. - + Failed to install the package {0}. Details: {1}. Non è stato possibile installare il pacchetto {0}. Dettagli: {1}. - + The install request {0} cannot be processed by installer {1}. La richiesta di installazione {0} non può essere elaborata dal programma di installazione di {1}. - + The NuGet package {0} is invalid. Il pacchetto NuGet {0} non è valido. - + The configured NuGet sources are invalid: {0}. Le origini NuGet configurate non sono valide: {0}. - + No NuGet sources are configured. Nessuna origine NuGet configurata. - + The operation was cancelled. Operazione annullata. - + {0} was not found in NuGet feeds {1}. {0} non è stato trovato nei feed NuGet {1}. - + The package {0} is not supported by installer {1}. Il pacchetto {0} non è supportato dal programma di installazione {1}. - + Failed to uninstall the package {0}. Details: {1}. Non è stato possibile disinstallare il pacchetto {0}. Dettagli: {1}. - + Failed to check the update for the package {0}. Details: {1}. Non è possibile verificare la presenza dell'aggiornamento per il pacchetto {0}. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ja.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ja.xlf index c5f379ce889..0c843818477 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ja.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ja.xlf @@ -25,7 +25,7 @@ パラメーター条件に循環依存関係が含まれています: [{0}]。パラメーターの現在の値を使用すると、パラメーターを決定論的に評価できるため、続行します。ただし、異なるパラメーターを持つインスタンス化によってエラーが発生する可能性があるため、テンプレートを確認する必要があります。 {0} is the dependency chain - + '{0}' should not contain empty items '{0}' に空の項目を含めることはできません {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ ファイル {0} は既に存在します。 - + Failed to download {0} from {1}. {1} からの {0} のダウンロードに失敗しました。 - + Failed to install the package {0}. Details: {1}. パッケージ {0} をインストールできませんでした。 詳細: {1}。 - + The install request {0} cannot be processed by installer {1}. インストール要求 {0} をインストーラー {1} で処理できません。 - + The NuGet package {0} is invalid. NuGet パッケージ {0} が無効です。 - + The configured NuGet sources are invalid: {0}. 構成済みの NuGet ソースが無効です: {0}。 - + No NuGet sources are configured. 構成された NuGet ソースがありません。 - + The operation was cancelled. 処理が取り消されました。 - + {0} was not found in NuGet feeds {1}. {0} が NuGet フィード {1} で見つかりません。 - + The package {0} is not supported by installer {1}. このパッケージ {0}はインストーラー {1} でサポートされていません - + Failed to uninstall the package {0}. Details: {1}. パッケージ {0} をアンインストールできませんでした。 詳細: {1}。 - + Failed to check the update for the package {0}. Details: {1}. パッケージ {0} の更新プログラムを確認できませんでした。 diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ko.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ko.xlf index 20feaa0739a..7618c0a15be 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ko.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ko.xlf @@ -25,7 +25,7 @@ 매개 변수 조건에 [{0}] 순환 종속성이 포함되어 있습니다. 매개 변수의 현재 값을 사용하여 매개 변수를 결정적으로 평가할 수 있으므로 계속 진행합니다. 그러나 다른 매개 변수가 있는 인스턴스화는 오류가 발생할 수 있으므로 템플릿을 검토해야 합니다. {0} is the dependency chain - + '{0}' should not contain empty items '{0}'에는 빈 항목이 없어야 합니다. {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ 파일 {0}이(가) 이미 있습니다. - + Failed to download {0} from {1}. {1}에서 {0}을(를) 다운로드하지 못했습니다. - + Failed to install the package {0}. Details: {1}. 패키지 {0}을(를) 설치하지 못했습니다. 세부 정보: {1}. - + The install request {0} cannot be processed by installer {1}. 설치 요청 {0}은(는) 설치 관리자 {1}에서 처리할 수 없습니다. - + The NuGet package {0} is invalid. NuGet 패키지 {0}이(가) 잘못되었습니다. - + The configured NuGet sources are invalid: {0}. 구성된 NuGet 원본이 잘못되었습니다. {0}. - + No NuGet sources are configured. NuGet 원본이 구성되지 않았습니다. - + The operation was cancelled. 작업이 취소되었습니다. - + {0} was not found in NuGet feeds {1}. {0}을(를) NuGet 피드 {1}에서 찾을 수 없습니다. - + The package {0} is not supported by installer {1}. 설치 관리자 {1}이(가) 패키지 {0}를(을) 지원하지 않습니다. - + Failed to uninstall the package {0}. Details: {1}. 패키지 {0}을(를) 설치하지 못했습니다. 세부 정보: {1}. - + Failed to check the update for the package {0}. Details: {1}. 패키지 {0}에 대한 업데이트를 확인하지 못했습니다. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pl.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pl.xlf index dcef15d2998..fc9b4fd2653 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pl.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pl.xlf @@ -25,7 +25,7 @@ Warunki parametru zawierają zależność cykliczną: [{0}]. Przy bieżących wartościach parametrów można deterministycznie ocenić parametry, a więc dalsze postępowanie. Należy jednak przejrzeć szablon, ponieważ utworzenie wystąpienia z różnymi parametrami może doprowadzić do błędu. {0} is the dependency chain - + '{0}' should not contain empty items Konfiguracja „{0}” nie powinna zawierać pustych elementów {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Plik {0} już istnieje. - + Failed to download {0} from {1}. Nie można pobrać {0} z {1}. - + Failed to install the package {0}. Details: {1}. Nie można zainstalować pakietu {0}. Szczegóły: {1}. - + The install request {0} cannot be processed by installer {1}. Nie można przetworzyć żądania instalacji {0} przez instalator {1}. - + The NuGet package {0} is invalid. Pakiet NuGet {0} jest nieprawidłowy. - + The configured NuGet sources are invalid: {0}. Skonfigurowane źródła pakietu NuGet są nieprawidłowe: {0}. - + No NuGet sources are configured. Nie skonfigurowano źródeł pakietu NuGet. - + The operation was cancelled. Operacja została anulowana. - + {0} was not found in NuGet feeds {1}. Nie znaleziono pakietu {0} w kanałach informacyjnych pakietu NuGet {1}. - + The package {0} is not supported by installer {1}. Pakiet {0} nie jest obsługiwany przez instalator {1}. - + Failed to uninstall the package {0}. Details: {1}. Nie można odinstalować pakietu {0}. Szczegóły: {1}. - + Failed to check the update for the package {0}. Details: {1}. Nie można sprawdzić aktualizacji dla pakietu {0}. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pt-BR.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pt-BR.xlf index a3aa67a4239..ec58b481f95 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pt-BR.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.pt-BR.xlf @@ -25,7 +25,7 @@ As condições de parâmetro contêm dependência cíclica: [{0}]. Com os valores atuais de parâmetros, é possível avaliar parâmetros de forma determinística, portanto, continuar. No entanto, o modelo deve ser revisado, pois a instanciação com parâmetros diferentes pode levar a um erro. {0} is the dependency chain - + '{0}' should not contain empty items '{0}' não deve conter itens vazios {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ O arquivo {0} já existe. - + Failed to download {0} from {1}. Falha no download {0} de {1}. - + Failed to install the package {0}. Details: {1}. Falha ao instalar o pacote {0}. Detalhes: {1}. - + The install request {0} cannot be processed by installer {1}. O pedido de instalação {0} não pode ser processado pelo instalador {1}. - + The NuGet package {0} is invalid. O pacote NuGet {0} é inválido. - + The configured NuGet sources are invalid: {0}. A fonte NuGet configurado é inválido: {0}. - + No NuGet sources are configured. Nenhuma fonte NuGet foi configurado. - + The operation was cancelled. A operação foi cancelada. - + {0} was not found in NuGet feeds {1}. {0} não foi encontrado no NuGet feeds {1}. - + The package {0} is not supported by installer {1}. O pacote{0} não é suportado pelo instalador {1}. - + Failed to uninstall the package {0}. Details: {1}. Falha ao desinstalar o pacote {0}. Detalhes: {1}. - + Failed to check the update for the package {0}. Details: {1}. Falha ao verificar a atualização do pacote {0}, diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ru.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ru.xlf index 75102b42fa6..85ff0a69545 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ru.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.ru.xlf @@ -25,7 +25,7 @@ Условия параметра содержат циклическую зависимость: [{0}]. С текущими значениями параметров возможно детерминированное вычисление параметров, поэтому работа продолжается. Тем не менее, следует проверить шаблон, поскольку при создании экземпляра с другими параметрами может возникнуть ошибка. {0} is the dependency chain - + '{0}' should not contain empty items «{0}» не должна содержать пустых элементов {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ Файл {0} уже существует. - + Failed to download {0} from {1}. Не удалось загрузить {0} из {1}. - + Failed to install the package {0}. Details: {1}. Не удалось установить пакет {0}. Сведения: {1}. - + The install request {0} cannot be processed by installer {1}. Запрос на {0} не может быть обработан установщиком {1}. - + The NuGet package {0} is invalid. Недопустимый пакет NuGet {0}. - + The configured NuGet sources are invalid: {0}. Настроенные источники NuGet недопустимы: {0}. - + No NuGet sources are configured. Нет настроенных источников NuGet. - + The operation was cancelled. Операция отменена. - + {0} was not found in NuGet feeds {1}. {0} не найден в веб-каналах NuGet {1}. - + The package {0} is not supported by installer {1}. Пакет {0} не поддерживается установщиком {1}. - + Failed to uninstall the package {0}. Details: {1}. Не удалось удалить пакет {0}. Сведения: {1}. - + Failed to check the update for the package {0}. Details: {1}. Не удалось проверить обновление для пакета {0}. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.tr.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.tr.xlf index 9bea388d911..45973ae443d 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.tr.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.tr.xlf @@ -25,7 +25,7 @@ Parametre koşulları döngüsel bağımlılık içeriyor: [{0}]. Parametrelerin geçerli değerleriyle parametrelerin belirlenimci değerlendirmesini gerçekleştirmek mümkün olduğu için devam ediliyor. Ancak farklı parametrelerle örnek oluşturma, hataya neden olabileceğinden şablon gözden geçiriliyor. {0} is the dependency chain - + '{0}' should not contain empty items '{0}' boş öğe içermemelidir {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ {0} dosyası zaten var. - + Failed to download {0} from {1}. {0}, {1} kaynağından indirilemedi. - + Failed to install the package {0}. Details: {1}. {0} paketi yüklenemedi. Ayrıntılar: {1}. - + The install request {0} cannot be processed by installer {1}. {0} yükleme isteği {1} yükleyicisi tarafından işlenemiyor. - + The NuGet package {0} is invalid. {0} NuGet paketi geçersiz. - + The configured NuGet sources are invalid: {0}. Yapılandırılan NuGet kaynakları geçersiz: {0}. - + No NuGet sources are configured. Hiçbir NuGet kaynağı yapılandırılmadı. - + The operation was cancelled. İşlem iptal edildi. - + {0} was not found in NuGet feeds {1}. {0}, {1} NuGet akışlarında bulunamadı. - + The package {0} is not supported by installer {1}. {0} paketi, {1} yükleyicisi tarafından desteklenmiyor. - + Failed to uninstall the package {0}. Details: {1}. {0} paketi yüklenemedi. Ayrıntılar: {1}. - + Failed to check the update for the package {0}. Details: {1}. {0} paketi için güncelleştirme denetimi başarısız oldu. diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hans.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hans.xlf index 2f6aeae2ab7..080fdad0891 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hans.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hans.xlf @@ -25,7 +25,7 @@ 参数条件包含循环依赖项: [{0}]。对于参数的当前值,可以确定性地计算参数,因此可以继续操作。但是,应该审阅该模板,因为具有不同参数的实例化可能会导致错误。 {0} is the dependency chain - + '{0}' should not contain empty items “{0}”不应包含空项 {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ 文件 {0} 已存在。 - + Failed to download {0} from {1}. 未能从 {1} 下载 {0}。 - + Failed to install the package {0}. Details: {1}. 未能安装包 {0}。 详细信息: {1}。 - + The install request {0} cannot be processed by installer {1}. 安装程序 {1} 无法处理安装请求 {0}。 - + The NuGet package {0} is invalid. NuGet 包 {0} 无效。 - + The configured NuGet sources are invalid: {0}. 配置的 NuGet 源无效: {0}。 - + No NuGet sources are configured. 未配置 NuGet 源。 - + The operation was cancelled. 操作被取消。 - + {0} was not found in NuGet feeds {1}. 在 NuGet 源 {1} 中未找到 {0}。 - + The package {0} is not supported by installer {1}. 安装程序 {1} 不支持包 {0}。 - + Failed to uninstall the package {0}. Details: {1}. 未能卸载包 {0}。 详细信息: {1}。 - + Failed to check the update for the package {0}. Details: {1}. 无法检查包 {0} 的更新。 diff --git a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hant.xlf b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hant.xlf index 9e0d2791437..e0783c7b9b3 100644 --- a/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hant.xlf +++ b/src/Microsoft.TemplateEngine.Edge/xlf/LocalizableStrings.zh-Hant.xlf @@ -25,7 +25,7 @@ 參數條件包含迴圈相依性: [{0}]。使用目前的參數值,可以確定性地評估參數,所以繼續進行。不過,應該檢閱範本,因為使用不同參數具現化可能會導致錯誤。 {0} is the dependency chain - + '{0}' should not contain empty items '{0}' 不應包含空白項目 {0} is JSON configuration for constraint @@ -232,61 +232,61 @@ 檔案 {0} 已經存在。 - + Failed to download {0} from {1}. 無法從 {1} 下載 {0}。 - + Failed to install the package {0}. Details: {1}. 無法安裝套件 {0}。 詳細資料: {1}。 - + The install request {0} cannot be processed by installer {1}. 安裝程式 {1} 無法處理安裝要求 {0}。 - + The NuGet package {0} is invalid. NuGet 套件 {0} 無效。 - + The configured NuGet sources are invalid: {0}. 設定的 NuGet 來源無效: {0}。 - + No NuGet sources are configured. 未設定任何 NuGet 來源。 - + The operation was cancelled. 作業已取消。 - + {0} was not found in NuGet feeds {1}. 在 NuGet 摘要 {1} 中找不到 {0}。 - + The package {0} is not supported by installer {1}. 安裝程式 {1} 不支援安裝套件 {0}。 - + Failed to uninstall the package {0}. Details: {1}. 無法取消安裝套件 {0}。 詳細資料: {1}。 - + Failed to check the update for the package {0}. Details: {1}. 無法檢查套件 {0} 的更新。 diff --git a/src/Microsoft.TemplateEngine.IDE/Bootstrapper.cs b/src/Microsoft.TemplateEngine.IDE/Bootstrapper.cs index a7b97d64450..678a2f65a18 100644 --- a/src/Microsoft.TemplateEngine.IDE/Bootstrapper.cs +++ b/src/Microsoft.TemplateEngine.IDE/Bootstrapper.cs @@ -1,13 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; @@ -124,7 +118,7 @@ public Task> GetTemplatesAsync(IEnumerable true; - filters ??= Array.Empty>(); + filters ??= []; } else { @@ -429,7 +423,7 @@ public IEnumerable Uninstall(IEnumerable paths) if (!paths.Any()) { - return Array.Empty(); + return []; } var task = GetManagedTemplatePackagesAsync(); diff --git a/src/Microsoft.TemplateEngine.IDE/Microsoft.TemplateEngine.IDE.csproj b/src/Microsoft.TemplateEngine.IDE/Microsoft.TemplateEngine.IDE.csproj index 73e54295376..3d51d28f92f 100644 --- a/src/Microsoft.TemplateEngine.IDE/Microsoft.TemplateEngine.IDE.csproj +++ b/src/Microsoft.TemplateEngine.IDE/Microsoft.TemplateEngine.IDE.csproj @@ -1,7 +1,7 @@ + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Helper package for adding Template Engine to IDEs true true diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IDeferredMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IDeferredMacro.cs index 724ebea34b8..7e8db6076e4 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IDeferredMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IDeferredMacro.cs @@ -1,13 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions { /// - /// An interface for macros created that can create the config from other config (deffered config). + /// An interface for macros created that can create the config from other config (deferred config). /// [Obsolete("Use IGeneratedSymbolConfig instead.")] public interface IDeferredMacro : IMacro diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IGeneratedSymbolConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IGeneratedSymbolConfig.cs index c4fffb219d6..5ceaffacec4 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IGeneratedSymbolConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IGeneratedSymbolConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IMacroDependency.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IMacroDependency.cs index 71bc2c5bbc6..698c34be892 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IMacroDependency.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IMacroDependency.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions { /// diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/BindSymbolEvaluator.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/BindSymbolEvaluator.cs index da873f766f1..adfaafef836 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/BindSymbolEvaluator.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/BindSymbolEvaluator.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Components; @@ -152,10 +147,10 @@ private void ProcessEvaluationResults(IVariableCollection variableCollection, IR string? prefix = null; string binding = configuredBinding; - if (configuredBinding.Contains(":")) + if (configuredBinding.Contains(':')) { - prefix = configuredBinding.Substring(0, configuredBinding.IndexOf(":")).Trim(); - binding = configuredBinding.Substring(configuredBinding.IndexOf(":") + 1).Trim(); + prefix = configuredBinding.Substring(0, configuredBinding.IndexOf(':')).Trim(); + binding = configuredBinding.Substring(configuredBinding.IndexOf(':') + 1).Trim(); } if (string.IsNullOrWhiteSpace(binding)) { @@ -216,18 +211,18 @@ private void ProcessEvaluationResults(IVariableCollection variableCollection, IR binding, string.Join(", ", successfulTasks.Select(t => $"{t.Source.DisplayName} (priority: {t.Source.Priority}): '{t.Value}'"))); var highestPriority = successfulTasks.Max(t => t.Source.Priority); - var highestPrioTasks = successfulTasks.Where(t => t.Source.Priority == highestPriority); - if (highestPrioTasks.Count() > 1) + var highestPriorityTasks = successfulTasks.Where(t => t.Source.Priority == highestPriority); + if (highestPriorityTasks.Count() > 1) { - string sourcesList = string.Join(", ", highestPrioTasks.Select(t => $"'{t.Source.DisplayName}'")); - string prefixesList = string.Join(", ", highestPrioTasks.Select(t => $"'{t.Source.SourcePrefix}:'")); + string sourcesList = string.Join(", ", highestPriorityTasks.Select(t => $"'{t.Source.DisplayName}'")); + string prefixesList = string.Join(", ", highestPriorityTasks.Select(t => $"'{t.Source.SourcePrefix}:'")); _logger.LogWarning(LocalizableStrings.BindSymbolEvaluator_Warning_ValueAvailableFromMultipleSources, configuredBinding, sourcesList, prefixesList); return null; } else { - _logger.LogDebug("'{0}' was selected for '{1}' as highest priority value.", highestPrioTasks.Single().Value, binding); - return highestPrioTasks.Single().Value; + _logger.LogDebug("'{0}' was selected for '{1}' as highest priority value.", highestPriorityTasks.Single().Value, binding); + return highestPriorityTasks.Single().Value; } } } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs index 0f4ab2e05a9..2d64bf11481 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseReplaceSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseReplaceSymbol.cs index a47c44242ad..7f45f022b56 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseReplaceSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseReplaceSymbol.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel @@ -11,7 +9,7 @@ public abstract class BaseReplaceSymbol : BaseSymbol { private protected BaseReplaceSymbol(string name, string? replaces) : base(name) { - ReplacementContexts = Array.Empty(); + ReplacementContexts = []; Replaces = replaces; } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseSymbol.cs index c68e3001b51..1c5659eefd9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseSymbol.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel { public abstract class BaseSymbol diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseValueSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseValueSymbol.cs index 29f15deb4c1..666889bd586 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseValueSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BaseValueSymbol.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BindSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BindSymbol.cs index ab3c27977f6..880a43d702d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BindSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/BindSymbol.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ComputedSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ComputedSymbol.cs index 576f648c2b1..a05df4586f9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ComputedSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ComputedSymbol.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ConditionedConfigurationElement.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ConditionedConfigurationElement.cs index 8c2fb274caf..b5604b9fe08 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ConditionedConfigurationElement.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ConditionedConfigurationElement.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Expressions.Cpp2; @@ -23,7 +22,7 @@ public abstract class ConditionedConfigurationElement public string? Condition { get; internal init; } /// - /// Stores the result of condition evaluation. should be done before accessting this property. + /// Stores the result of condition evaluation. should be done before accessing this property. /// /// when the property is accessed prior to method is called. public bool ConditionResult diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/CustomFileGlobModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/CustomFileGlobModel.cs index 6402b58f6a7..91afdfb31bf 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/CustomFileGlobModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/CustomFileGlobModel.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/DerivedSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/DerivedSymbol.cs index c4d6aea813a..09d9e7d4381 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/DerivedSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/DerivedSymbol.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ExtendedFileSource.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ExtendedFileSource.cs index d81e7f2ce6c..b48dd82470b 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ExtendedFileSource.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ExtendedFileSource.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel @@ -21,19 +18,19 @@ internal ExtendedFileSource() { } /// Defines the files to be just copied when instantiating template. Operations will not be applied to them. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList CopyOnly { get; internal init; } = Array.Empty(); + public IReadOnlyList CopyOnly { get; internal init; } = []; /// /// Defines the files to be include when instantiating template. Operations will be applied to them. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList Include { get; internal init; } = Array.Empty(); + public IReadOnlyList Include { get; internal init; } = []; /// /// Defines the files to be excluded when instantiating template. These files will not be processed during template instantiation. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList Exclude { get; internal init; } = Array.Empty(); + public IReadOnlyList Exclude { get; internal init; } = []; /// /// Defines the files to be renamed when instantiating the template. The key is a source file name, the value is the final file name. @@ -55,7 +52,7 @@ internal ExtendedFileSource() { } /// /// A list of additional source information which gets added to the top-level source information, based on evaluation the corresponding "source.modifiers.condition". /// - public IReadOnlyList Modifiers { get; internal init; } = Array.Empty(); + public IReadOnlyList Modifiers { get; internal init; } = []; internal static ExtendedFileSource FromJObject(JObject jObject) { diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/GeneratedSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/GeneratedSymbol.cs index a5d25f0ddaa..291621f5638 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/GeneratedSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/GeneratedSymbol.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ParameterSymbol.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ParameterSymbol.cs index 3fc52ac2906..4127cec846a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ParameterSymbol.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ParameterSymbol.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; @@ -251,7 +249,7 @@ private static TemplateParameterPrecedence GetPrecedence(bool isRequired, bool i return null; } - // Attribute parseable as a bool - so we do not want to present it as a condition + // Attribute parsable as a bool - so we do not want to present it as a condition if (isRequiredToken!.TryParseBool(out _)) { return null; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PostActionModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PostActionModel.cs index b2a67343315..958dc603a76 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PostActionModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PostActionModel.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Validation; @@ -64,7 +62,7 @@ public string? Description /// /// Gets the list of arguments to which file renames should be applied. /// - public IReadOnlyList ApplyFileRenamesToArgs { get; internal init; } = Array.Empty(); + public IReadOnlyList ApplyFileRenamesToArgs { get; internal init; } = []; /// /// Gets a value indicating whether the file renames should be applied to manual instructions. @@ -96,7 +94,7 @@ internal static IReadOnlyList LoadListFromJArray(JArray? jArray bool continueOnError = action.ToBool(nameof(ContinueOnError)); string? postActionCondition = action.ToString(nameof(Condition)); bool applyFileRenamesToManualInstructions = action.ToBool(nameof(ApplyFileRenamesToManualInstructions)); - IReadOnlyList applyFileRenamesToArgs = action.ArrayAsStrings(nameof(ApplyFileRenamesToArgs)) ?? Array.Empty(); + IReadOnlyList applyFileRenamesToArgs = action.ArrayAsStrings(nameof(ApplyFileRenamesToArgs)) ?? []; if (postActionId != null && !postActionIds.Add(postActionId)) { diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PrimaryOutputModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PrimaryOutputModel.cs index 4014f7f5784..3a791151afe 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PrimaryOutputModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/PrimaryOutputModel.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ReplacementContext.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ReplacementContext.cs index 248728b4c5e..be69f3f74a5 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ReplacementContext.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/ReplacementContext.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel @@ -53,7 +51,7 @@ internal static IReadOnlyList FromJObject(JObject jObject) } else { - return Array.Empty(); + return []; } } } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SourceModifier.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SourceModifier.cs index 05e7caa9f93..c17ec8db80b 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SourceModifier.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SourceModifier.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel { /// @@ -17,19 +14,19 @@ internal SourceModifier() { } /// Defines the files to be just copied when instantiating template. Operations will not be applied to them. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList CopyOnly { get; internal init; } = Array.Empty(); + public IReadOnlyList CopyOnly { get; internal init; } = []; /// /// Defines the files to be include when instantiating template. Operations will be applied to them. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList Include { get; internal init; } = Array.Empty(); + public IReadOnlyList Include { get; internal init; } = []; /// /// Defines the files to be excluded when instantiating template. These files will not be processed during template instantiation. /// Can be glob. If single value is given, it can be also a filename where from to read this configuration. /// - public IReadOnlyList Exclude { get; internal init; } = Array.Empty(); + public IReadOnlyList Exclude { get; internal init; } = []; /// /// Defines the files to be renamed when instantiating the template. The key is a source file name, the value is the final file name. diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SymbolValueFormsModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SymbolValueFormsModel.cs index e070e3e8e95..7f8ec6fea4d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SymbolValueFormsModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/SymbolValueFormsModel.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms; using Newtonsoft.Json.Linq; @@ -18,7 +15,7 @@ internal SymbolValueFormsModel(IReadOnlyList globalForms) public IReadOnlyList GlobalForms { get; } - internal static SymbolValueFormsModel Empty { get; } = new SymbolValueFormsModel(Array.Empty()); + internal static SymbolValueFormsModel Empty { get; } = new SymbolValueFormsModel([]); // by default, symbols get the "identity" value form, for a direct replacement internal static SymbolValueFormsModel Default { get; } = new SymbolValueFormsModel(new[] { IdentityValueFormFactory.FormIdentifier }); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/TemplateConfigModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/TemplateConfigModel.cs index f1a7c315fc8..06a35b816f4 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/TemplateConfigModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ConfigModel/TemplateConfigModel.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Runtime.InteropServices; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -23,7 +19,6 @@ namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel public sealed class TemplateConfigModel { private const string NameSymbolName = "name"; - private readonly ILogger? _logger; private readonly Dictionary _forms = SetupValueFormMapForTemplate(); // validation entries: @@ -47,12 +42,12 @@ internal TemplateConfigModel(string identity) } Identity = identity; - Symbols = Array.Empty(); + Symbols = []; } private TemplateConfigModel(JObject source, ILogger? logger, string? baselineName = null) { - _logger = logger; + ILogger? logger1 = logger; string? identity = source.ToString(nameof(Identity)); if (string.IsNullOrWhiteSpace(identity)) @@ -187,14 +182,14 @@ private TemplateConfigModel(JObject source, ILogger? logger, string? baselineNam { if (prop.Value is not JObject obj) { - _logger?.LogWarning(LocalizableStrings.SimpleConfigModel_Error_Constraints_InvalidSyntax, nameof(Constraints).ToLowerInvariant()); + logger1?.LogWarning(LocalizableStrings.SimpleConfigModel_Error_Constraints_InvalidSyntax, nameof(Constraints).ToLowerInvariant()); continue; } string? type = obj.ToString(nameof(TemplateConstraintInfo.Type)); if (string.IsNullOrWhiteSpace(type)) { - _logger?.LogWarning(LocalizableStrings.SimpleConfigModel_Error_Constraints_MissingType, obj.ToString(), nameof(TemplateConstraintInfo.Type).ToLowerInvariant()); + logger1?.LogWarning(LocalizableStrings.SimpleConfigModel_Error_Constraints_MissingType, obj.ToString(), nameof(TemplateConstraintInfo.Type).ToLowerInvariant()); continue; } obj.TryGetValue(nameof(TemplateConstraintInfo.Args), StringComparison.OrdinalIgnoreCase, out JToken? args); @@ -277,7 +272,7 @@ public IReadOnlyDictionary Tags /// /// Gets the list of template short names ("shortName" JSON property). /// - public IReadOnlyList ShortNameList { get; internal init; } = Array.Empty(); + public IReadOnlyList ShortNameList { get; internal init; } = []; /// /// Gets the list of post actions defined for the template ("postActions" JSON property). @@ -292,7 +287,7 @@ public IReadOnlyList PostActionModels /// /// Gets the list of template primary outputs ("primaryOutputs" JSON property). /// - public IReadOnlyList PrimaryOutputs { get; internal init; } = Array.Empty(); + public IReadOnlyList PrimaryOutputs { get; internal init; } = []; /// /// Gets version expression which defines which generator versions is supported by the template ("generatorVersions" JSON property). @@ -312,12 +307,12 @@ public IReadOnlyList PostActionModels /// /// Gets the list of classifications of the template ("classifications" JSON property). /// - public IReadOnlyList Classifications { get; internal init; } = Array.Empty(); + public IReadOnlyList Classifications { get; internal init; } = []; /// /// Gets the list of guids defined in the template ("guids" JSON property). /// - public IReadOnlyList Guids { get; internal init; } = Array.Empty(); + public IReadOnlyList Guids { get; internal init; } = []; /// /// Gets the source name defined in the template ("sourceName" JSON property). @@ -337,12 +332,12 @@ internal init /// /// Gets the list of sources defined in the template ("sources" JSON property). /// - public IReadOnlyList Sources { get; internal init; } = Array.Empty(); + public IReadOnlyList Sources { get; internal init; } = []; /// /// Gets the list of constraints defined in the template ("constraints" JSON property). /// - public IReadOnlyList Constraints { get; internal init; } = Array.Empty(); + public IReadOnlyList Constraints { get; internal init; } = []; /// /// Gets the list of symbols defined in the template ("symbols" JSON property). @@ -394,7 +389,7 @@ internal init /// /// Gets the list of custom operations defined for the template for specific files ("specialCustomOperations" JSON property). /// - public IReadOnlyList SpecialCustomOperations { get; internal init; } = Array.Empty(); + public IReadOnlyList SpecialCustomOperations { get; internal init; } = []; internal BaseSymbol NameSymbol { get; private init; } = SetupDefaultNameSymbol(null); @@ -410,13 +405,11 @@ internal init /// /// The stream containing template configuration in JSON format. /// The logger to use for reporting errors/messages. - /// The filepath of template configuration (optional, used for logging). + /// The file path of template configuration (optional, used for logging). public static TemplateConfigModel FromStream(Stream content, ILogger? logger = null, string? filename = null) { - using (TextReader tr = new StreamReader(content, System.Text.Encoding.UTF8, true)) - { - return FromTextReader(tr, logger); - } + using TextReader tr = new StreamReader(content, System.Text.Encoding.UTF8, true); + return FromTextReader(tr, logger); } /// @@ -424,7 +417,7 @@ public static TemplateConfigModel FromStream(Stream content, ILogger? logger = n /// /// The string containing template configuration in JSON format. /// The logger to use for reporting errors/messages. - /// The filepath of template configuration (optional, used for logging). + /// The file path of template configuration (optional, used for logging). public static TemplateConfigModel FromString(string content, ILogger? logger = null, string? filename = null) { if (string.IsNullOrWhiteSpace(content)) @@ -432,18 +425,14 @@ public static TemplateConfigModel FromString(string content, ILogger? logger = n throw new ArgumentException($"'{nameof(content)}' cannot be null or whitespace.", nameof(content)); } - using (TextReader tr = new StringReader(content)) - { - return FromTextReader(tr, logger); - } + using TextReader tr = new StringReader(content); + return FromTextReader(tr, logger); } internal static TemplateConfigModel FromTextReader(TextReader content, ILogger? logger = null) { - using (JsonReader r = new JsonTextReader(content)) - { - return new TemplateConfigModel(JObject.Load(r), logger, null); - } + using JsonReader r = new JsonTextReader(content); + return new TemplateConfigModel(JObject.Load(r), logger, null); } internal static TemplateConfigModel FromJObject(JObject source, ILogger? logger = null, string? baselineName = null) @@ -550,9 +539,9 @@ private static Dictionary SetupValueFormMapForTemplate(JObje // setup the forms defined by the template configuration. // if any have the same name as a default, the default is overridden. - IReadOnlyDictionary templateDefinedforms = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, nameof(Forms)); + IReadOnlyDictionary templateDefinedForms = source.ToJTokenDictionary(StringComparer.OrdinalIgnoreCase, nameof(Forms)); - foreach (KeyValuePair form in templateDefinedforms) + foreach (KeyValuePair form in templateDefinedForms) { if (form.Value is JObject o) { @@ -586,7 +575,7 @@ private static IReadOnlyList SetupImplicitBindSymbols() bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); if (!isWindows) { - return Array.Empty(); + return []; } //on Windows we implicitly bind OS to avoid likely breaking change. //this environment variable is commonly used in conditions when using run script post action. diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationEffects.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationEffects.cs index 0f1890a47ea..7e53fea6afc 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationEffects.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationEffects.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationResult.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationResult.cs index 14ca8654847..22a98a8ec63 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationResult.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CreationResult.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CryptoRandom.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CryptoRandom.cs index a7dc5759a15..4bb248f6a8c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CryptoRandom.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/CryptoRandom.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Security.Cryptography; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects @@ -19,10 +18,8 @@ public CryptoRandom(int ignoredSeed) { } public static int NextInt(int minValue, int maxValue) { - using (CryptoRandom random = new CryptoRandom()) - { - return random.Next(minValue, maxValue); - } + using CryptoRandom random = new CryptoRandom(); + return random.Next(minValue, maxValue); } public int Next() diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.Interfaces.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.Interfaces.cs index cc36b3e0a1b..d885ca7c99c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.Interfaces.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.Interfaces.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.cs index 3035c00f2ba..438575cfe56 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/DirectoryBasedTemplate.cs @@ -1,13 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/EvaluatorSelector.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/EvaluatorSelector.cs index 28a187337a4..d76173c2ecc 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/EvaluatorSelector.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/EvaluatorSelector.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Expressions.Cpp; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileRenameGenerator.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileRenameGenerator.cs index 5129b6f46e6..430cea4366e 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileRenameGenerator.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileRenameGenerator.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceHierarchicalPathMatcher.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceHierarchicalPathMatcher.cs index eaf7ba2b4d6..0cda5b56a1d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceHierarchicalPathMatcher.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceHierarchicalPathMatcher.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceMatchInfo.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceMatchInfo.cs index 6d6ad283341..5915bf321fe 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceMatchInfo.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/FileSourceMatchInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { internal class FileSourceEvaluable diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunConfig.cs index 0e7563aea8c..3f3e2d390db 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel; @@ -11,16 +9,16 @@ namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { internal class GlobalRunConfig { - public IReadOnlyList Operations { get; init; } = Array.Empty(); + public IReadOnlyList Operations { get; init; } = []; public IVariableConfig VariableSetup { get; init; } = VariableConfig.Default; - public IReadOnlyList Replacements { get; init; } = Array.Empty(); + public IReadOnlyList Replacements { get; init; } = []; - public IReadOnlyList CustomOperations { get; init; } = Array.Empty(); + public IReadOnlyList CustomOperations { get; init; } = []; - public IReadOnlyList SymbolNames { get; init; } = Array.Empty(); + public IReadOnlyList SymbolNames { get; init; } = []; - public IReadOnlyList Macros { get; init; } = Array.Empty(); + public IReadOnlyList Macros { get; init; } = []; } } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunSpec.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunSpec.cs index 0eaa5da71fb..92a73dc80fc 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunSpec.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/GlobalRunSpec.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -45,7 +42,7 @@ internal GlobalRunSpec( { foreach ((string glob, GlobalRunConfig runConfig) in configuration.SpecialOperationConfig) { - IReadOnlyList specialOps = Array.Empty(); + IReadOnlyList specialOps = []; if (runConfig != null) { @@ -60,11 +57,11 @@ internal GlobalRunSpec( Special = specials; } - public IReadOnlyList Include { get; private set; } = Array.Empty(); + public IReadOnlyList Include { get; private set; } = []; - public IReadOnlyList Exclude { get; private set; } = Array.Empty(); + public IReadOnlyList Exclude { get; private set; } = []; - public IReadOnlyList CopyOnly { get; private set; } = Array.Empty(); + public IReadOnlyList CopyOnly { get; private set; } = []; public IReadOnlyList Operations { get; } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IOperationConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IOperationConfig.cs index 8db40eac60d..3fbf890af21 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IOperationConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IOperationConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IRunnableProjectConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IRunnableProjectConfig.cs index da69682cef8..350dbd674bd 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IRunnableProjectConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/IRunnableProjectConfig.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ListGlobbingPatternMatcher.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ListGlobbingPatternMatcher.cs index 7ca249df0c2..8175b82ada3 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ListGlobbingPatternMatcher.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ListGlobbingPatternMatcher.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.Designer.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.Designer.cs deleted file mode 100644 index 831f996e407..00000000000 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,595 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Orchestrator.RunnableProjects.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Id of the post action '{0}' at index '{1}' is not unique. Only the first post action that uses this id will be localized.. - /// - internal static string Authoring_CONFIG0201_PostActionIdIsNotUnique { - get { - return ResourceManager.GetString("Authoring_CONFIG0201_PostActionIdIsNotUnique", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Post action at index '{0}' should have an 'actionId' to declare the action to be executed.. - /// - internal static string Authoring_CONFIG0202_PostActionMustHaveActionId { - get { - return ResourceManager.GetString("Authoring_CONFIG0202_PostActionMustHaveActionId", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'id' of the manual instruction '{0}' at index {1} is not unique. Only the first manual instruction that uses this id will be localized.. - /// - internal static string Authoring_CONFIG0203_ManualInstructionIdIsNotUnique { - get { - return ResourceManager.GetString("Authoring_CONFIG0203_ManualInstructionIdIsNotUnique", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The argument '{0}' configured in '{1}' is not listed in '{2}' and will be skipped for processing.. - /// - internal static string Authoring_CONFIG0204_UnknownArgumentForReplace { - get { - return ResourceManager.GetString("Authoring_CONFIG0204_UnknownArgumentForReplace", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Parameter conditions contain cyclic dependency: [{0}] that is preventing deterministic evaluation.. - /// - internal static string Authoring_CyclicDependencyInSymbols { - get { - return ResourceManager.GetString("Authoring_CyclicDependencyInSymbols", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Localization file should only contain elements with type 'string'. Remove elements that are not strings.. - /// - internal static string Authoring_InvalidJsonElementInLocalizationFile { - get { - return ResourceManager.GetString("Authoring_InvalidJsonElementInLocalizationFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to In localization file under the post action with id '{1}', there are localized strings for manual instruction(s) with ids '{0}'. These manual instructions do not exist in the template.json file and should be removed from localization file.. - /// - internal static string Authoring_InvalidManualInstructionLocalizationIndex { - get { - return ResourceManager.GetString("Authoring_InvalidManualInstructionLocalizationIndex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Choice parameter '{0}' is invalid. It allows multiple values ('AllowMultipleValues=true'), while some of the configured choices contain separator characters ({1}). Invalid choices: {2}. - /// - internal static string Authoring_InvalidMultichoiceSymbol { - get { - return ResourceManager.GetString("Authoring_InvalidMultichoiceSymbol", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Post action(s) with id(s) '{0}' specified in the localization file do not exist in the template.json file. Remove the localized strings from the localization file.. - /// - internal static string Authoring_InvalidPostActionLocalizationIndex { - get { - return ResourceManager.GetString("Authoring_InvalidPostActionLocalizationIndex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' could not be parsed as a regular expression. - /// - internal static string Authoring_InvalidRegex { - get { - return ResourceManager.GetString("Authoring_InvalidRegex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to One or more postActions have a malformed or missing manualInstructions value.. - /// - internal static string Authoring_MalformedPostActionManualInstructions { - get { - return ResourceManager.GetString("Authoring_MalformedPostActionManualInstructions", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Missing '{0}'.. - /// - internal static string Authoring_MissingValue { - get { - return ResourceManager.GetString("Authoring_MissingValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A non-bool DataType was specified for a regexMatch type symbol. - /// - internal static string Authoring_NonBoolDataTypeForRegexMatch { - get { - return ResourceManager.GetString("Authoring_NonBoolDataTypeForRegexMatch", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Source '{0}' in template does not exist.. - /// - internal static string Authoring_SourceDoesNotExist { - get { - return ResourceManager.GetString("Authoring_SourceDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Source location '{0}' is outside the specified install source location.. - /// - internal static string Authoring_SourceIsOutsideInstallSource { - get { - return ResourceManager.GetString("Authoring_SourceIsOutsideInstallSource", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Source must be a directory, but '{0}' is a file.. - /// - internal static string Authoring_SourceMustBeDirectory { - get { - return ResourceManager.GetString("Authoring_SourceMustBeDirectory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template configuration {0} is missing common information:. - /// - internal static string Authoring_TemplateMissingCommonInformation { - get { - return ResourceManager.GetString("Authoring_TemplateMissingCommonInformation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load template from {0}:. - /// - internal static string Authoring_TemplateNotInstalled { - get { - return ResourceManager.GetString("Authoring_TemplateNotInstalled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load template from {0}. - ///Details: {1}. - /// - internal static string Authoring_TemplateNotInstalled_Message { - get { - return ResourceManager.GetString("Authoring_TemplateNotInstalled_Message", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template root is outside the specified install source location.. - /// - internal static string Authoring_TemplateRootOutsideInstallSource { - get { - return ResourceManager.GetString("Authoring_TemplateRootOutsideInstallSource", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Bind symbol '{0}': failed to convert value '{1}' to datatype '{2}'. The symbol processing is skipped.. - /// - internal static string BindSymbolEvaluator_Warning_ConversionFailure { - get { - return ResourceManager.GetString("BindSymbolEvaluator_Warning_ConversionFailure", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Bind symbol '{0}': failed to convert default value '{1}' to datatype '{2}'. The default value is skipped.. - /// - internal static string BindSymbolEvaluator_Warning_DefaultValueConversionFailure { - get { - return ResourceManager.GetString("BindSymbolEvaluator_Warning_DefaultValueConversionFailure", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to evaluate bind symbol '{0}', it will be skipped.. - /// - internal static string BindSymbolEvaluator_Warning_EvaluationError { - get { - return ResourceManager.GetString("BindSymbolEvaluator_Warning_EvaluationError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to evaluate binding '{0}', its value is available from multiple sources: {1}. Use the prefixed value ({2}) in template configuration instead.. - /// - internal static string BindSymbolEvaluator_Warning_ValueAvailableFromMultipleSources { - get { - return ResourceManager.GetString("BindSymbolEvaluator_Warning_ValueAvailableFromMultipleSources", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template authoring error encountered while processing macro '{0}': Variable '{1}'. Neither source nor fallback variable was found.. - /// - internal static string CoalesceMacro_Exception_MissedVariables { - get { - return ResourceManager.GetString("CoalesceMacro_Exception_MissedVariables", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unrecognized evaluator: '{0}'.. - /// - internal static string EvaluatorSelector_Exception_UnknownEvaluator { - get { - return ResourceManager.GetString("EvaluatorSelector_Exception_UnknownEvaluator", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The high port bound '{0}' is greater than the maximum allowed, '{1}' will be used instead.. - /// - internal static string GeneratePortNumberConfig_Warning_InvalidHighBound { - get { - return ResourceManager.GetString("GeneratePortNumberConfig_Warning_InvalidHighBound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The low port bound '{0}' is less than the minimum allowed, '{1}' will be used instead.. - /// - internal static string GeneratePortNumberConfig_Warning_InvalidLowBound { - get { - return ResourceManager.GetString("GeneratePortNumberConfig_Warning_InvalidLowBound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The low port bound '{0}' is greater the high port bound '{1}', the default range [{2}-{3}] will be used instead.. - /// - internal static string GeneratePortNumberConfig_Warning_InvalidLowHighBound { - get { - return ResourceManager.GetString("GeneratePortNumberConfig_Warning_InvalidLowHighBound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': array '{1}' should contain JSON objects with property non-empty '{2}' when '{3}' is '{4}'.. - /// - internal static string JoinMacroConfig_Exception_ValuePropertyIsEmpty { - get { - return ResourceManager.GetString("JoinMacroConfig_Exception_ValuePropertyIsEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to read or parse localization file {0}, it will be skipped from further processing.. - /// - internal static string LocalizationModelDeserializer_Error_FailedToParse { - get { - return ResourceManager.GetString("LocalizationModelDeserializer_Error_FailedToParse", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Locale '{0}' does not match any known cultures.. - /// - internal static string LocalizationModelDeserializer_Error_UnknownLocale { - get { - return ResourceManager.GetString("LocalizationModelDeserializer_Error_UnknownLocale", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The method '{0}' must be called prior '{1}' property reading.. - /// - internal static string MacroConfig_Exception_AccessToDependencies { - get { - return ResourceManager.GetString("MacroConfig_Exception_AccessToDependencies", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': array '{1}' should contain JSON objects.. - /// - internal static string MacroConfig_Exception_ArrayShouldContainObjects { - get { - return ResourceManager.GetString("MacroConfig_Exception_ArrayShouldContainObjects", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': '{1}' is not a valid JSON.. - /// - internal static string MacroConfig_Exception_InvalidJSON { - get { - return ResourceManager.GetString("MacroConfig_Exception_InvalidJSON", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': the regex pattern '{1}' is invalid.. - /// - internal static string MacroConfig_Exception_InvalidRegex { - get { - return ResourceManager.GetString("MacroConfig_Exception_InvalidRegex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}' of type '{1}' should have '{2}' property defined.. - /// - internal static string MacroConfig_Exception_MissingMandatoryProperty { - get { - return ResourceManager.GetString("MacroConfig_Exception_MissingMandatoryProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': array '{1}' should contain JSON objects with property '{2}'.. - /// - internal static string MacroConfig_Exception_MissingValueProperty { - get { - return ResourceManager.GetString("MacroConfig_Exception_MissingValueProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': '{1}' should be a valid JSON array.. - /// - internal static string MacroConfig_Exception_ValueShouldBeArray { - get { - return ResourceManager.GetString("MacroConfig_Exception_ValueShouldBeArray", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': '{1}' should be a boolean value.. - /// - internal static string MacroConfig_Exception_ValueShouldBeBoolean { - get { - return ResourceManager.GetString("MacroConfig_Exception_ValueShouldBeBoolean", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': '{1}' should be an integer value.. - /// - internal static string MacroConfig_Exception_ValueShouldBeInteger { - get { - return ResourceManager.GetString("MacroConfig_Exception_ValueShouldBeInteger", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': '{1}' should be a string value.. - /// - internal static string MacroConfig_Exception_ValueShouldBeString { - get { - return ResourceManager.GetString("MacroConfig_Exception_ValueShouldBeString", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' was not processed due to the next issues in dependencises: '{1}'.. - /// - internal static string MacroProcessing_Warning_DependencyErrors { - get { - return ResourceManager.GetString("MacroProcessing_Warning_DependencyErrors", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to process macro '{0}' of type '{1}'.. - /// - internal static string MacroProcessingException_Message { - get { - return ResourceManager.GetString("MacroProcessingException_Message", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated symbol '{0}': type '{1}' is unknown, processing is skipped.. - /// - internal static string MacroProcessor_Warning_UnknownMacro { - get { - return ResourceManager.GetString("MacroProcessor_Warning_UnknownMacro", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The symbol '{0}': unable to find a form '{1}', the further processing of the symbol will be skipped.. - /// - internal static string RunnableProjectConfig_OperationSetup_UnknownForm { - get { - return ResourceManager.GetString("RunnableProjectConfig_OperationSetup_UnknownForm", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Variable [{0}] already added with value [{1}]. Cannot add it as implicit variable with value of self.. - /// - internal static string RunnableProjectGenerator_CannotAddImplicitChoice { - get { - return ResourceManager.GetString("RunnableProjectGenerator_CannotAddImplicitChoice", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template configuration must be a file, but {0} is not a file.. - /// - internal static string RunnableProjectGenerator_Exception_ConfigShouldBeFile { - get { - return ResourceManager.GetString("RunnableProjectGenerator_Exception_ConfigShouldBeFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template localization configuration must be a file, but {0} is not a file.. - /// - internal static string RunnableProjectGenerator_Exception_LocaleConfigShouldBeFile { - get { - return ResourceManager.GetString("RunnableProjectGenerator_Exception_LocaleConfigShouldBeFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template configuration {0} is not valid.. - /// - internal static string RunnableProjectGenerator_Exception_TemplateValidationFailed { - get { - return ResourceManager.GetString("RunnableProjectGenerator_Exception_TemplateValidationFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template is not compatible with generator version: allowed versions: {0}, generator version: {1}.. - /// - internal static string RunnableProjectGenerator_Exception_TemplateVersionNotSupported { - get { - return ResourceManager.GetString("RunnableProjectGenerator_Exception_TemplateVersionNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Localization file {0} is not compatible with base configuration {1}, and will be skipped.. - /// - internal static string RunnableProjectGenerator_Warning_LocFileSkipped { - get { - return ResourceManager.GetString("RunnableProjectGenerator_Warning_LocFileSkipped", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load additional configuration file {0}, the file does not exist.. - /// - internal static string SimpleConfigModel_AuthoringException_MergeConfiguration_FileNotFound { - get { - return ResourceManager.GetString("SimpleConfigModel_AuthoringException_MergeConfiguration_FileNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to load additional configuration file {0}. Additional configuration file names must end with '.{1}'.. - /// - internal static string SimpleConfigModel_AuthoringException_MergeConfiguration_InvalidFileName { - get { - return ResourceManager.GetString("SimpleConfigModel_AuthoringException_MergeConfiguration_InvalidFileName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' should contain objects.. - /// - internal static string SimpleConfigModel_Error_Constraints_InvalidSyntax { - get { - return ResourceManager.GetString("SimpleConfigModel_Error_Constraints_InvalidSyntax", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Constraint definition '{0}' does not contain mandatory property '{1}'.. - /// - internal static string SimpleConfigModel_Error_Constraints_MissingType { - get { - return ResourceManager.GetString("SimpleConfigModel_Error_Constraints_MissingType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found disallowed value for IsRequired property: [{0}], expected boolean value.. - /// - internal static string Symbol_Error_IsRequiredNotABool { - get { - return ResourceManager.GetString("Symbol_Error_IsRequiredNotABool", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found disallowed value for IsRequired property: [{0}], expected boolean or string (condition) value. - /// - internal static string Symbol_Error_IsRequiredNotABoolOrString { - get { - return ResourceManager.GetString("Symbol_Error_IsRequiredNotABoolOrString", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The symbol '{0}' of type '{1}' is incorrect: mandatory property '{2}' is not set. The symbol will be skipped.. - /// - internal static string SymbolModel_Error_MandatoryPropertyMissing { - get { - return ResourceManager.GetString("SymbolModel_Error_MandatoryPropertyMissing", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.resx b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.resx index 5e2d0c0d1c4..c284032b70b 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.resx +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizableStrings.resx @@ -281,7 +281,7 @@ Details: {1} {0} - macro variable name, {1} - macro type (not localized). - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/LocalizationModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/LocalizationModel.cs index 3344b275ffa..55143767d66 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/LocalizationModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/LocalizationModel.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/ParameterSymbolLocalizationModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/ParameterSymbolLocalizationModel.cs index 9223c503697..f0698ee7b8a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/ParameterSymbolLocalizationModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/ParameterSymbolLocalizationModel.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/PostActionLocalizationModel.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/PostActionLocalizationModel.cs index 375ad5d40f0..36253b560c0 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/PostActionLocalizationModel.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/PostActionLocalizationModel.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization { internal class PostActionLocalizationModel diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/TemplateLocalizationInfo.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/TemplateLocalizationInfo.cs index 226e6847b36..784bf77a7d5 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/TemplateLocalizationInfo.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Localization/TemplateLocalizationInfo.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizationModelDeserializer.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizationModelDeserializer.cs index 411f80c77eb..0ab11ac769c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizationModelDeserializer.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/LocalizationModelDeserializer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization; @@ -30,7 +27,6 @@ public static LocalizationModel Deserialize(IFile file) _ = file ?? throw new ArgumentNullException(nameof(file)); JObject srcObject = file.ReadJObjectFromIFile(); - var parameterLocalizations = new Dictionary(); List<(string Key, string Value)> localizedStrings = srcObject.Properties() .Select(p => p.Value.Type == JTokenType.String ? (p.Name, p.Value.ToString()) : throw new Exception(LocalizableStrings.Authoring_InvalidJsonElementInLocalizationFile)) @@ -131,8 +127,7 @@ private static IReadOnlyDictionary LoadPost // Split them using '/' and store together with the localized string. IEnumerable<(IEnumerable NameParts, string LocalizedString)> strings = localizedStrings .Where(s => s.Key.StartsWith("postActions" + KeySeparator)) - .Select(s => (s.Key.Split(KeySeparator).AsEnumerable().Skip(1), s.Value)) - .ToList(); + .Select(s => (s.Key.Split(KeySeparator).AsEnumerable().Skip(1), s.Value)); foreach (var postActionParts in strings.GroupBy(p => p.NameParts.FirstOrDefault())) { diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessingException.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessingException.cs index 97a76e62063..7fc574b3a73 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessingException.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessingException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessor.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessor.cs index e3bf0d01005..c673be30b04 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessor.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/MacroProcessor.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; @@ -106,7 +103,7 @@ private static HashSet GetDependentMacros(IMacroConfig config, IRe foreach (string dependent in macroWithDep.Dependencies) { - IMacroConfig macro = allMacroConfigs.FirstOrDefault(mc => mc.VariableName == dependent); + IMacroConfig? macro = allMacroConfigs.FirstOrDefault(mc => mc.VariableName == dependent); if (macro != null) { dependents.Add(macro); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseGeneratedSymbolMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseGeneratedSymbolMacro.cs index 5c5aeaf2595..1ae6f257f19 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseGeneratedSymbolMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseGeneratedSymbolMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; @@ -35,7 +34,7 @@ public void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCo } /// - /// Base class for the macro defined via generated symbol, that may run undeterministially and implements deterministic mode for the macro. + /// Base class for the macro defined via generated symbol, that may run non-deterministically and implements deterministic mode for the macro. /// Note: this class only implements deterministic mode for the macro as . To implement deterministic mode for direct generated symbol evaluation, use . /// /// The macro config. @@ -45,7 +44,7 @@ internal abstract class BaseNondeterministicMacro : BaseGeneratedSymbolMacro< } /// - /// Base class for the macro defined via generated symbol, that may run undeterministially and implements deterministic mode for the macro as generated symbol. + /// Base class for the macro defined via generated symbol, that may run non-deterministically and implements deterministic mode for the macro as generated symbol. /// /// The macro config. internal abstract class BaseNondeterministicGenSymMacro : BaseNondeterministicMacro, IDeterministicModeMacro, IDeterministicModeMacro where T : BaseMacroConfig, IMacroConfig diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacro.cs index 793741cb415..1ac8940898d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacroConfig.cs index 67c1eb94bf2..7dfda10fd30 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/BaseMacroConfig.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.TemplateEngine.Core; @@ -206,7 +203,7 @@ protected void PopulateMacroConfigDependencies( NullLogger.Instance, condition, new VariableCollection(null, symbols.ToDictionary(s => s, s => s as object)), - out var evaluableExpressionError, + out var _, referencedVariablesKeys); referencedVariablesKeys.ForEach(PopulateMacroConfigDependency); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacro.cs index edaf41b7ff5..94fa812acd8 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacroConfig.cs index 9fbd34b36b1..0f6749e7dfb 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacroConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacro.cs index 6d54c508587..7a63659f221 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacroConfig.cs index a00f6dac0e8..641c927ecde 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacro.cs index 026b6185f1c..0a8d1698758 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacroConfig.cs index 4ae42cb37cc..c549e40616e 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacroConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs index 67f8d612bf1..a8d957593c5 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacroConfig.cs index 6af36b42627..1f1370b1aeb 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/EvaluateMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros @@ -27,7 +25,7 @@ internal EvaluateMacroConfig(string variableName, string? dataType, string condi } } - internal string Condition { get; private set; } + internal string Condition { get; } internal ConditionStringEvaluator Evaluator { get; private set; } = EvaluatorSelector.SelectStringEvaluator(DefaultEvaluator); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberConfig.cs index 29dc4929f29..bd066056f04 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberConfig.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; using System.Net; using System.Net.Sockets; using Microsoft.Extensions.Logging; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberMacro.cs index ed4749782a1..1802c86111a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GuidMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GuidMacro.cs index e8b7985922e..606c5478152 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GuidMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GuidMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; @@ -41,7 +40,7 @@ private void EvaluateInternal(Guid g, IEngineEnvironmentSettings environmentSett // Not breaking any dependencies on exact param names and on the // case insensitive matching of parameters (https://github.com/dotnet/templating/blob/7e14ef44/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs#L726) - // we need to introduce new parameters - with distinc naming for upper- and lower- casing replacements + // we need to introduce new parameters - with distinct naming for upper- and lower- casing replacements string legacyName = config.VariableName + "-" + config.Format[i]; string newName = config.VariableName + (isUpperCase ? GuidMacroConfig.UpperCaseDenominator : GuidMacroConfig.LowerCaseDenominator) + diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacro.cs index 29b22b9b692..8d4a2071284 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacro.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacroConfig.cs index dd1d9ab0f3c..baa2b89d7e0 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; @@ -15,11 +13,11 @@ internal class JoinMacroConfig : BaseMacroConfig, IM private const string SymbolsTypePropertyName = "type"; private const string SymbolsValuePropertyName = "value"; - internal JoinMacroConfig(JoinMacro macro, string variableName, string? dataType, IReadOnlyList<(JoinType, string)> symbols, string separator = "", bool removeEmptyValues = false) + internal JoinMacroConfig(JoinMacro macro, string variableName, string? dataType, IReadOnlyList<(JoinType, string)> symbols, string? separator = "", bool removeEmptyValues = false) : base(macro, variableName, dataType) { Symbols = symbols ?? throw new ArgumentNullException(nameof(symbols)); - Separator = separator; + Separator = separator ?? string.Empty; RemoveEmptyValues = removeEmptyValues; } @@ -35,12 +33,12 @@ internal JoinMacroConfig(JoinMacro macro, IGeneratedSymbolConfig generatedSymbol foreach (JToken entry in jArray) { - if (entry is not JObject jobj) + if (entry is not JObject jObj) { throw new TemplateAuthoringException(string.Format(LocalizableStrings.MacroConfig_Exception_ArrayShouldContainObjects, generatedSymbolConfig.VariableName, SymbolsPropertyName), generatedSymbolConfig.VariableName); } - JoinType type = jobj.ToEnum(SymbolsTypePropertyName, JoinType.Const, ignoreCase: true); - string? value = jobj.ToString(SymbolsValuePropertyName) + JoinType type = jObj.ToEnum(SymbolsTypePropertyName, JoinType.Const, ignoreCase: true); + string? value = jObj.ToString(SymbolsValuePropertyName) ?? throw new TemplateAuthoringException( string.Format( LocalizableStrings.MacroConfig_Exception_MissingValueProperty, @@ -73,7 +71,7 @@ internal enum JoinType Ref } - internal IReadOnlyList<(JoinType Type, string Value)> Symbols { get; private set; } + internal IReadOnlyList<(JoinType Type, string Value)> Symbols { get; } internal string Separator { get; private set; } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/NowMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/NowMacro.cs index 695a59b6080..bdc419a1cad 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/NowMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/NowMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacro.cs index 44297c9282d..e5df5a14321 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -17,7 +16,6 @@ internal class ProcessValueFormMacro : BaseMacro public override void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, ProcessValueFormMacroConfig config) { - string? value = string.Empty; if (!vars.TryGetValue(config.SourceVariable, out object working)) { environmentSettings.Host.Logger.LogDebug("[{macro}]: Source variable '{sourceVar}' was not found, skipping processing for macro '{var}'.", nameof(ProcessValueFormMacro), config.SourceVariable, config.VariableName); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacroConfig.cs index df1fdf8bc51..1e2027cfd46 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ProcessValueFormMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs index 3b1b04e2659..eca9ed7f1e3 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacro.cs index 3bbe4463b4f..b4871399e62 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacroConfig.cs index 4e8d7b28796..fc8792bacac 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; @@ -37,12 +35,12 @@ internal RegexMacroConfig(RegexMacro macro, IGeneratedSymbolConfig generatedSymb foreach (JToken entry in jArray) { - if (entry is not JObject jobj) + if (entry is not JObject jObj) { throw new TemplateAuthoringException(string.Format(LocalizableStrings.MacroConfig_Exception_ArrayShouldContainObjects, generatedSymbolConfig.VariableName, StepsPropertyName), generatedSymbolConfig.VariableName); } - string? regex = jobj.ToString(StepsRegexPropertyName); - string? replacement = jobj.ToString(StepsReplacementPropertyName); + string? regex = jObj.ToString(StepsRegexPropertyName); + string? replacement = jObj.ToString(StepsReplacementPropertyName); if (string.IsNullOrEmpty(regex)) { @@ -61,7 +59,7 @@ internal RegexMacroConfig(RegexMacro macro, IGeneratedSymbolConfig generatedSymb Steps = steps; } - internal string Source { get; private set; } + internal string Source { get; } internal IReadOnlyList<(string Regex, string Replacement)> Steps { get; private set; } diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacro.cs index 79925734058..08ec4f6dbed 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacroConfig.cs index 9dc132ca12c..a1ba4818e12 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacroConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacro.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacro.cs index 3da7a843967..02ee72e38ba 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacro.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacro.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacroConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacroConfig.cs index 6aa350920ad..df256725ef1 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacroConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacroConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json.Linq; @@ -35,12 +34,12 @@ internal SwitchMacroConfig(SwitchMacro macro, IGeneratedSymbolConfig generatedSy foreach (JToken entry in jArray) { - if (entry is not JObject jobj) + if (entry is not JObject jObj) { throw new TemplateAuthoringException(string.Format(LocalizableStrings.MacroConfig_Exception_ArrayShouldContainObjects, generatedSymbolConfig.VariableName, CasesPropertyName), generatedSymbolConfig.VariableName); } - string? condition = jobj.ToString(CasesConditionPropertyName); - string? value = jobj.ToString(CasesValuePropertyName) + string? condition = jObj.ToString(CasesConditionPropertyName); + string? value = jObj.ToString(CasesValuePropertyName) ?? throw new TemplateAuthoringException( string.Format( LocalizableStrings.MacroConfig_Exception_MissingValueProperty, @@ -55,7 +54,7 @@ internal SwitchMacroConfig(SwitchMacro macro, IGeneratedSymbolConfig generatedSy internal ConditionStringEvaluator Evaluator { get; private set; } = EvaluatorSelector.SelectStringEvaluator(DefaultEvaluator); - internal IReadOnlyList<(string? Condition, string Value)> Cases { get; private set; } + internal IReadOnlyList<(string? Condition, string Value)> Cases { get; } public void ResolveSymbolDependencies(IReadOnlyList symbols) { diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.csproj b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.csproj index 4d7ed66b67e..32609e9dc4d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.csproj +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.csproj @@ -1,13 +1,18 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) An extension for Template Engine that allows projects that still run to be used as templates true - true + + + + annotations + + @@ -22,18 +27,8 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + @@ -42,6 +37,4 @@ - - diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/BalancedNestingConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/BalancedNestingConfig.cs index 58f1a103d61..6aa866e2b6a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/BalancedNestingConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/BalancedNestingConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalBlockCommentConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalBlockCommentConfig.cs index 12caa28c424..e7690085e06 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalBlockCommentConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalBlockCommentConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Operations; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalConfig.cs index 1f7c3f71355..cdd90807f15 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; @@ -65,8 +63,8 @@ internal static IReadOnlyList ConditionalSetup(ConditionalTy case ConditionalType.HashSignLineComment: // Most line comment conditional tags use: // But for this one, the '#' comment symbol is all that's needed, so it uses an empty keyword prefix. - // So we end up with regular conditionals suchs as '#if', '#else' - // and actionables such as '##if' + // So we end up with regular conditionals such as '#if', '#else' + // and actions such as '##if' ConditionalKeywords keywords = new ConditionalKeywords() { KeywordPrefix = string.Empty diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalCustomConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalCustomConfig.cs index 64f7810892f..e3bc5cbedf5 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalCustomConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalCustomConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Operations; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalKeywords.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalKeywords.cs index 2394bb2cbdb..9989aa22014 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalKeywords.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalKeywords.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.OperationConfig diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalLineCommentConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalLineCommentConfig.cs index 9ba29d70b33..932874e4f84 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalLineCommentConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ConditionalLineCommentConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Operations; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/FlagsConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/FlagsConfig.cs index d263234ef24..413acce85d9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/FlagsConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/FlagsConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/IncludeConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/IncludeConfig.cs index 7618c654081..09bfbec4e83 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/IncludeConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/IncludeConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/OperationConfigDefault.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/OperationConfigDefault.cs index 025419191aa..1531e39eea6 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/OperationConfigDefault.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/OperationConfigDefault.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.OperationConfig { internal class OperationConfigDefault diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/RegionConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/RegionConfig.cs index fc9fb0c2aca..23ab8774482 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/RegionConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/RegionConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ReplacementConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ReplacementConfig.cs index 86a109d2ec6..1682d2211ec 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ReplacementConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/OperationConfig/ReplacementConfig.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Parameter.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Parameter.cs index f7ed2e729e4..b001ce09746 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Parameter.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Parameter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterBasedVariableCollection.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterBasedVariableCollection.cs index 934a028cd9e..46bd53e75f9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterBasedVariableCollection.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterBasedVariableCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; using Microsoft.TemplateEngine.Core; @@ -28,7 +27,7 @@ public ParameterBasedVariableCollection( : base(parent, values) => ParameterSetData = parameterSetData; - public IParameterSetData ParameterSetData { get; private set; } + public IParameterSetData ParameterSetData { get; } public static ParameterBasedVariableCollection Root(IParameterSetData parameterSetData) => new(null, new Dictionary(), parameterSetData); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterConverter.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterConverter.cs index bb223fc4b17..d95ab92aa46 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterConverter.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ParameterConverter.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils @@ -62,7 +59,7 @@ internal static bool TryConvertParameterValueToType( return null; } - if (!literal.Contains("\"")) + if (!literal.Contains('"')) { if (TryResolveBooleanValue(literal, out bool parsedBool)) { @@ -231,7 +228,7 @@ private static bool TryResolveNullValue(string? literal, out object? parsed) return false; } - private static bool TryResolveFloatValue(string? literal, out double parsed) => ParserExtensions.DoubleTryParseСurrentOrInvariant(literal, out parsed); + private static bool TryResolveFloatValue(string? literal, out double parsed) => ParserExtensions.DoubleTryParseCurrentOrInvariant(literal, out parsed); private static bool TryResolveIntegerValue(string? literal, out long parsed) => long.TryParse(literal, out parsed); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PostAction.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PostAction.cs index 30ac4a6b6d5..dc0cd53df3a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PostAction.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PostAction.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core; @@ -28,7 +25,7 @@ public PostAction(string? description, string? manualInstructions, Guid actionId public Guid ActionId { get; } - public bool ContinueOnError { get; private set; } + public bool ContinueOnError { get; } public IReadOnlyDictionary Args { get; } = new Dictionary(); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PrimaryOutput.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PrimaryOutput.cs index 7976399e14b..3a183ee49d7 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PrimaryOutput.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/PrimaryOutput.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunSpec.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunSpec.cs index 8b720be4154..4a8ddcedfc0 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunSpec.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunSpec.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.ITemplate.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.ITemplate.cs index c3e0e906e8e..3ee93765a36 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.ITemplate.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.ITemplate.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -22,11 +19,11 @@ internal partial class RunnableProjectConfig : ITemplate string ITemplateLocator.ConfigPlace => ConfigFile?.FullPath ?? throw new InvalidOperationException("Configuration file is not initialized, are you using test constructor?"); - IFileSystemInfo? ITemplate.LocaleConfiguration => _localizationInfo?.File; + IFileSystemInfo? ITemplate.LocaleConfiguration => Localization?.File; IFileSystemInfo? ITemplate.HostSpecificConfiguration => _hostConfigFile; - string? IExtendedTemplateLocator.LocaleConfigPlace => _localizationInfo?.File.FullPath; + string? IExtendedTemplateLocator.LocaleConfigPlace => Localization?.File.FullPath; string? IExtendedTemplateLocator.HostConfigPlace => _hostConfigFile?.FullPath; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.cs index 1ec4595dccd..649ff3b855c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectConfig.cs @@ -1,14 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; using System.Text; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -47,7 +41,6 @@ internal partial class RunnableProjectConfig : DirectoryBasedTemplate, IRunnable private static readonly string[] DefaultPlaceholderFilenames = new[] { "-.-", "_._" }; private readonly Dictionary _guidToGuidPrefixMap = new(); - private readonly TemplateLocalizationInfo? _localizationInfo; private readonly IFile? _hostConfigFile; private IReadOnlyList? _sources; @@ -72,7 +65,7 @@ internal RunnableProjectConfig(IEngineEnvironmentSettings settings, IGenerator g try { LocalizationModel locModel = LocalizationModelDeserializer.Deserialize(localeConfigFile); - _localizationInfo = new TemplateLocalizationInfo(ParseLocFileName(localeConfigFile) ?? CultureInfo.InvariantCulture, locModel, localeConfigFile); + Localization = new TemplateLocalizationInfo(ParseLocFileName(localeConfigFile) ?? CultureInfo.InvariantCulture, locModel, localeConfigFile); } catch (Exception ex) { @@ -130,7 +123,7 @@ public GlobalRunConfig GlobalOperationConfig if (customGlobModel.ConditionResult) { // only add the special if the condition is true - OperationConfigDefault defaultParams = defaultSpecials.FirstOrDefault(x => x.Glob == customGlobModel.Glob); + OperationConfigDefault? defaultParams = defaultSpecials.FirstOrDefault(x => x.Glob == customGlobModel.Glob); defaultParams ??= OperationConfigDefault.Default; @@ -168,7 +161,7 @@ public GlobalRunConfig GlobalOperationConfig /// internal IMountPoint SourceMountPoint { get; } - internal TemplateLocalizationInfo? Localization => _localizationInfo; + internal TemplateLocalizationInfo? Localization { get; } internal IReadOnlyList SymbolFilenameReplacements { @@ -180,11 +173,11 @@ internal IReadOnlyList SymbolFilenameReplacements } internal override IReadOnlyDictionary Localizations => - _localizationInfo is null + Localization is null ? new Dictionary() : new Dictionary() { - { _localizationInfo.Locale, _localizationInfo } + { Localization.Locale, Localization } }; internal override IReadOnlyDictionary HostFiles => @@ -277,11 +270,9 @@ private static IReadOnlyList TryReadConfigFromFile(IReadOnlyList } else { - using (Stream excludeList = sourceFile!.Parent!.FileInfo(singleConfig)!.OpenRead()) - using (TextReader reader = new StreamReader(excludeList, Encoding.UTF8, true, 4096, true)) - { - return reader.ReadToEnd().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); - } + using Stream excludeList = sourceFile!.Parent!.FileInfo(singleConfig)!.OpenRead(); + using TextReader reader = new StreamReader(excludeList, Encoding.UTF8, true, 4096, true); + return reader.ReadToEnd().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } } return configs; @@ -487,12 +478,11 @@ private void GenerateFileReplacementsForSymbol(string fileRename, string sourceV private List ProduceGeneratedSymbolsMacroConfig() { - var generatedSymbolsConfigs = ConfigurationModel.Symbols.OfType().ToList(); Dictionary generatedSymbolMacros = EngineEnvironmentSettings.Components.OfType() .ToDictionary(m => m.Type, m => m); var generatedMacroConfigs = new List(); - foreach (var generatedSymbolConfig in generatedSymbolsConfigs) + foreach (var generatedSymbolConfig in ConfigurationModel.Symbols.OfType()) { if (generatedSymbolMacros.TryGetValue(generatedSymbolConfig.Type, out var generatedSymbolMacro)) { @@ -545,9 +535,9 @@ private List EvaluateSources(IVariableCollection rootVariab continue; } - IReadOnlyList topIncludePattern = TryReadConfigFromFile(source.Include, ConfigFile, IncludePatternDefaults).ToList(); - IReadOnlyList topExcludePattern = TryReadConfigFromFile(source.Exclude, ConfigFile, ExcludePatternDefaults).ToList(); - IReadOnlyList topCopyOnlyPattern = TryReadConfigFromFile(source.CopyOnly, ConfigFile, CopyOnlyPatternDefaults).ToList(); + IReadOnlyList topIncludePattern = TryReadConfigFromFile(source.Include, ConfigFile, IncludePatternDefaults); + IReadOnlyList topExcludePattern = TryReadConfigFromFile(source.Exclude, ConfigFile, ExcludePatternDefaults); + IReadOnlyList topCopyOnlyPattern = TryReadConfigFromFile(source.CopyOnly, ConfigFile, CopyOnlyPatternDefaults); FileSourceEvaluable topLevelPatterns = new FileSourceEvaluable(topIncludePattern, topExcludePattern, topCopyOnlyPattern); Dictionary fileRenamesFromSource = source.Rename.ToDictionary(x => x.Key, x => x.Value); @@ -559,9 +549,9 @@ private List EvaluateSources(IVariableCollection rootVariab { if (modifier.EvaluateCondition(Logger, rootVariableCollection)) { - IReadOnlyList modifierIncludes = TryReadConfigFromFile(modifier.Include, ConfigFile, Array.Empty()); - IReadOnlyList modifierExcludes = TryReadConfigFromFile(modifier.Exclude, ConfigFile, Array.Empty()); - IReadOnlyList modifierCopyOnly = TryReadConfigFromFile(modifier.CopyOnly, ConfigFile, Array.Empty()); + IReadOnlyList modifierIncludes = TryReadConfigFromFile(modifier.Include, ConfigFile, []); + IReadOnlyList modifierExcludes = TryReadConfigFromFile(modifier.Exclude, ConfigFile, []); + IReadOnlyList modifierCopyOnly = TryReadConfigFromFile(modifier.CopyOnly, ConfigFile, []); FileSourceEvaluable modifierPatterns = new FileSourceEvaluable(modifierIncludes, modifierExcludes, modifierCopyOnly); modifierList.Add(modifierPatterns); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs index 16a396b9b75..ee34ce4bb38 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectGenerator.cs @@ -1,12 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; @@ -420,15 +414,14 @@ private static ICreationResult GetCreationResult(IRunnableProjectConfig runnable private class LegacyTemplate : ITemplate { private readonly ScannedTemplateInfo _templateInfo; - private readonly IGenerator _generator; internal LegacyTemplate(ScannedTemplateInfo templateInfo, IGenerator generator) { _templateInfo = templateInfo; - _generator = generator; + Generator = generator; } - public IGenerator Generator => _generator; + public IGenerator Generator { get; } public IFileSystemInfo Configuration => _templateInfo.ConfigFile; @@ -452,7 +445,7 @@ internal LegacyTemplate(ScannedTemplateInfo templateInfo, IGenerator generator) public string Identity => _templateInfo.ConfigurationModel.Identity; - public Guid GeneratorId => _generator.Id; + public Guid GeneratorId => Generator.Id; public string? GroupIdentity => _templateInfo.ConfigurationModel.GroupIdentity; @@ -470,9 +463,9 @@ internal LegacyTemplate(ScannedTemplateInfo templateInfo, IGenerator generator) public string ConfigPlace => _templateInfo.ConfigFile.FullPath; - public string? LocaleConfigPlace => throw new NotImplementedException(); + public string LocaleConfigPlace => throw new NotImplementedException(); - public string? HostConfigPlace => throw new NotImplementedException(); + public string HostConfigPlace => throw new NotImplementedException(); public string? ThirdPartyNotices => _templateInfo.ConfigurationModel.ThirdPartyNotices; @@ -488,7 +481,7 @@ internal LegacyTemplate(ScannedTemplateInfo templateInfo, IGenerator generator) public IReadOnlyList ValidationErrors => _templateInfo.ValidationErrors; - public ILocalizationLocator? Localization => throw new NotImplementedException(); + public ILocalizationLocator Localization => throw new NotImplementedException(); #region Obsolete members diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectOrchestrator.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectOrchestrator.cs index 911ff0cdd41..3f179c85106 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectOrchestrator.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/RunnableProjectOrchestrator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ScannedTemplateInfo.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ScannedTemplateInfo.cs index 0c0e879c3ba..ddfd20d0478 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ScannedTemplateInfo.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ScannedTemplateInfo.cs @@ -1,11 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -16,7 +12,7 @@ namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { /// /// This class represent the template discovered during scanning. It is not ready to be run. - /// It also returns information about all the localizations available for the template and all host files avaialble for the template. + /// It also returns information about all the localizations available for the template and all host files available for the template. /// Before running the template the caller should select localization and host file to use. /// Use to load template for running. /// diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ActionValidationCheck.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ActionValidationCheck.cs index ee9b18913d9..38632b0acd8 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ActionValidationCheck.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ActionValidationCheck.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Validation diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidationInfo.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidationInfo.cs index 8517401c12b..11b407acf09 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidationInfo.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidationInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using System.Globalization; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidatorFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidatorFactory.cs index 1cf453c2c27..b517b74d1af 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidatorFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ITemplateValidatorFactory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Validation diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryLocalizationValidationFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryLocalizationValidationFactory.cs index 3abfb4d8c24..c61a4e3f0b6 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryLocalizationValidationFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryLocalizationValidationFactory.cs @@ -1,12 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Localization; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryValidationFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryValidationFactory.cs index 7224a74b3ed..ff5f07cf78c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryValidationFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MandatoryValidationFactory.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MultiValidationCheck.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MultiValidationCheck.cs index f0c7743b8f3..7d0013e0a00 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MultiValidationCheck.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/MultiValidationCheck.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ValidationManager.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ValidationManager.cs index 6237f23b9a0..ce9e3e828a9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ValidationManager.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Validation/ValidationManager.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueFormRegistry.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueFormRegistry.cs index 933e198494c..95b9c2e7251 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueFormRegistry.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueFormRegistry.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ActionableValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ActionableValueFormFactory.cs index 486bad092e3..d88dd60575f 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ActionableValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ActionableValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/BaseValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/BaseValueFormFactory.cs index c3f25455a2b..ccd721b547a 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/BaseValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/BaseValueFormFactory.cs @@ -1,30 +1,26 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { /// /// Base implementation of . - /// When implementing a value form inherit from or or instead. + /// When implementing a value form inherit from or or instead. /// internal abstract class BaseValueFormFactory : IValueFormFactory { - private readonly string _identifier; - protected BaseValueFormFactory(string identifier) { if (string.IsNullOrWhiteSpace(identifier)) { throw new ArgumentException($"'{nameof(identifier)}' cannot be null or whitespace.", nameof(identifier)); } - _identifier = identifier; + Identifier = identifier; } - public string Identifier => _identifier; + public string Identifier { get; } public abstract IValueForm Create(string? name = null); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ChainValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ChainValueFormFactory.cs index 76c573fe2a0..0a6eed43825 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ChainValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ChainValueFormFactory.cs @@ -1,12 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { - internal class ChainValueFormFactory : DependantValueFormFactory> + internal class ChainValueFormFactory : DependentValueFormFactory> { internal const string FormIdentifier = "chain"; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ConfigurableValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ConfigurableValueFormFactory.cs index a2ed7804b6c..f01570a0256 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ConfigurableValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/ConfigurableValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms @@ -36,7 +34,7 @@ public override IValueForm Create(string? name = null) }; } - protected abstract T ReadConfiguration(JObject jobject); + protected abstract T ReadConfiguration(JObject jObject); protected abstract string Process(string value, T? configuration); diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNamespaceValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNamespaceValueFormFactory.cs index 76219dc38cb..28bec0c0b20 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNamespaceValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNamespaceValueFormFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Text; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Utilities; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependantValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependentValueFormFactory.cs similarity index 74% rename from src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependantValueFormFactory.cs rename to src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependentValueFormFactory.cs index 829f51db1c4..1ac8da24845 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependantValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DependentValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms @@ -10,18 +8,18 @@ namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms /// /// Base implementation for a for a that has a configuration of type and needs to know all the forms defined to process a value form. /// - internal abstract class DependantValueFormFactory : BaseValueFormFactory where T : class + internal abstract class DependentValueFormFactory : BaseValueFormFactory where T : class { - protected DependantValueFormFactory(string identifier) : base(identifier) { } + protected DependentValueFormFactory(string identifier) : base(identifier) { } public override IValueForm FromJObject(string name, JObject? configuration) { if (configuration != null) { T config = ReadConfiguration(configuration); - return new DependantValueForm(name, this, config); + return new DependentValueForm(name, this, config); } - return new DependantValueForm(name, this, null); + return new DependentValueForm(name, this, null); } public override IValueForm Create(string? name = null) @@ -30,22 +28,22 @@ public override IValueForm Create(string? name = null) { name = Identifier; } - return new DependantValueForm(name!, this, null) + return new DependentValueForm(name!, this, null) { IsDefault = true }; } - protected abstract T ReadConfiguration(JObject jobject); + protected abstract T ReadConfiguration(JObject jObject); protected abstract string Process(string value, T? configuration, IReadOnlyDictionary otherForms); - private class DependantValueForm : BaseValueForm + private class DependentValueForm : BaseValueForm { - private readonly DependantValueFormFactory _factory; + private readonly DependentValueFormFactory _factory; private readonly T? _configuration; - internal DependantValueForm(string name, DependantValueFormFactory factory, T? configuration) : base(name, factory.Identifier) + internal DependentValueForm(string name, DependentValueFormFactory factory, T? configuration) : base(name, factory.Identifier) { _factory = factory; _configuration = configuration; diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseInvariantValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseInvariantValueFormFactory.cs index 4d79551017f..f9bc6945807 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseInvariantValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseInvariantValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { internal class FirstLowerCaseInvariantValueFormFactory : ActionableValueFormFactory diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseValueFormFactory.cs index 9a0a88f4c66..0469e434a83 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstLowerCaseValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { internal class FirstLowerCaseValueFormFactory : ActionableValueFormFactory diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseInvariantValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseInvariantValueFormFactory.cs index 721787dccfe..56b9d7e3f4e 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseInvariantValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseInvariantValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { internal class FirstUpperCaseInvariantValueFormFactory : ActionableValueFormFactory diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseValueFormFactory.cs index e8f5466a25f..7ce9d3f6cdf 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/FirstUpperCaseValueFormFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; - namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms { internal class FirstUpperCaseValueFormFactory : ActionableValueFormFactory diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/IValueForm.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/IValueForm.cs index 64eab51a56b..9366ec4bcdd 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/IValueForm.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/IValueForm.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ConfigModel; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/KebabCaseValueFormFactory.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/KebabCaseValueFormFactory.cs index fa0079e6b7f..a4ed854534c 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/KebabCaseValueFormFactory.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/KebabCaseValueFormFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; using System.Text.RegularExpressions; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/VariableConfig.cs b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/VariableConfig.cs index 294dbe3e713..7383fb0903e 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/VariableConfig.cs +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/VariableConfig.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects @@ -20,13 +19,13 @@ private VariableConfig( Expand = expand; } - public IReadOnlyDictionary Sources { get; private init; } + public IReadOnlyDictionary Sources { get; } - public IReadOnlyList Order { get; private init; } + public IReadOnlyList Order { get; } - public string? FallbackFormat { get; private init; } + public string? FallbackFormat { get; } - public bool Expand { get; private init; } + public bool Expand { get; } internal static IVariableConfig Default { get; } = new VariableConfig( diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.cs.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.cs.xlf index dc00ae924f9..f731c774d49 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.cs.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.cs.xlf @@ -176,8 +176,8 @@ Podrobnosti: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - '{0}' se nezpracovalo kvůli dalším problémům v závislostech: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + {0} se nezpracovalo kvůli dalším problémům v závislostech: {1}. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.de.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.de.xlf index 58913d38121..a4f34d7e304 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.de.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.de.xlf @@ -176,7 +176,7 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. '{0}' wurde aufgrund der nächsten Probleme in Abhängigkeiten nicht verarbeitet: '{1}'. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.es.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.es.xlf index e5fbea9ae0c..183a972e721 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.es.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.es.xlf @@ -176,8 +176,8 @@ Detalles: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - '{0}' no se procesó debido a los siguientes problemas en las dependencias: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + "{0}" no se ha procesado debido a los siguientes problemas en las dependencias: "{1}". {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.fr.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.fr.xlf index 097ada95691..0cfdfa2f221 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.fr.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.fr.xlf @@ -176,8 +176,8 @@ détails : {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - '{0}' n’a pas été traitée en raison des problèmes suivants dans les dépendances : '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + «{0}» n’a pas été traité en raison des problèmes suivants dans les dépendances : «{1}». {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.it.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.it.xlf index d9e0951beab..22148f34e64 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.it.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.it.xlf @@ -176,7 +176,7 @@ Dettagli: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. '{0}' non è stato elaborato a causa dei problemi successivi nelle dipendenze: '{1}'. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ja.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ja.xlf index 56c5fbbcb07..88a2318ee54 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ja.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ja.xlf @@ -176,7 +176,7 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. 依存関係の次の問題のため、'{0}' は処理されませんでした: '{1}'。 {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ko.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ko.xlf index 7b1d594a6f3..4c8401b4387 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ko.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ko.xlf @@ -176,8 +176,8 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - 종속성의 다음 문제인 '{1}'으로 인해 '{0}'이(가) 처리되지 않았습니다. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + 종속성의 다음 문제인 '{1}'(으)로 인해 '{0}'이(가) 처리되지 않았습니다. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pl.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pl.xlf index e1d454add9b..ac515117938 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pl.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pl.xlf @@ -176,8 +176,8 @@ Szczegóły: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - Element „{0}” nie został przetworzony z powodu następnych problemów w zależnościach: „{1}”. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + Makro „{0}” nie zostało przetworzone z powodu następnych problemów w zależnościach: „{1}”. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pt-BR.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pt-BR.xlf index 5082fb63152..4e47b5c7229 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pt-BR.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.pt-BR.xlf @@ -176,7 +176,7 @@ Detalhes: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. '{0}' não foi processado devido aos próximos problemas nas dependências: '{1}'. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ru.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ru.xlf index f4a1c432ee1..b4078baf271 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ru.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.ru.xlf @@ -176,8 +176,8 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - "{0}" не обработано из-за следующих проблем в зависимостях: "{1}". + '{0}' was not processed due to the next issues in dependencies: '{1}'. + "{0}" не обработан из-за следующих проблем в зависимостях: "{1}". {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.tr.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.tr.xlf index ace2036ae50..8419acce6b4 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.tr.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.tr.xlf @@ -176,8 +176,8 @@ Ayrıntılar: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - '{0}' bağımlılıklarda bulunan sonraki sorunlar nedeniyle işlenmedi: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. + '{0}', bağımlılıklarda bulunan aşağıdaki sorunlar nedeniyle işlenmedi: '{1}'. {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hans.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hans.xlf index b099096e4ea..ce7c678c45d 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hans.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hans.xlf @@ -176,7 +176,7 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. + '{0}' was not processed due to the next issues in dependencies: '{1}'. 由于依赖项中的下一个问题: "{1}",未处理 "{0}"。 {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hant.xlf b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hant.xlf index 953ac22654a..c69bdf729a9 100644 --- a/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hant.xlf +++ b/src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/xlf/LocalizableStrings.zh-Hant.xlf @@ -176,8 +176,8 @@ Details: {1} erty name. - '{0}' was not processed due to the next issues in dependencises: '{1}'. - 因為相依性中的下一個問題,所以未處理 '{0}': '{1}'。 + '{0}' was not processed due to the next issues in dependencies: '{1}'. + 因為相依性中的下一個問題: '{1}',所以未處理 '{0}'。 {0} - macro name, {1} - dependent macros errors diff --git a/src/Microsoft.TemplateEngine.Utils/ArrayExtensions.cs b/src/Microsoft.TemplateEngine.Utils/ArrayExtensions.cs index 9518670129e..827ae31843d 100644 --- a/src/Microsoft.TemplateEngine.Utils/ArrayExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/ArrayExtensions.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Utils { public static class ArrayExtensions diff --git a/src/Microsoft.TemplateEngine.Utils/AsyncLazy.cs b/src/Microsoft.TemplateEngine.Utils/AsyncLazy.cs index e7e5faef336..6703bd9bb7f 100644 --- a/src/Microsoft.TemplateEngine.Utils/AsyncLazy.cs +++ b/src/Microsoft.TemplateEngine.Utils/AsyncLazy.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; namespace Microsoft.TemplateEngine.Utils { diff --git a/src/Microsoft.TemplateEngine.Utils/BaselineInfo.cs b/src/Microsoft.TemplateEngine.Utils/BaselineInfo.cs index 3364fae371b..5d05b4158f0 100644 --- a/src/Microsoft.TemplateEngine.Utils/BaselineInfo.cs +++ b/src/Microsoft.TemplateEngine.Utils/BaselineInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/CacheParameter.cs b/src/Microsoft.TemplateEngine.Utils/CacheParameter.cs index 8bf9fc8bfff..99506c37068 100644 --- a/src/Microsoft.TemplateEngine.Utils/CacheParameter.cs +++ b/src/Microsoft.TemplateEngine.Utils/CacheParameter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/CacheTag.cs b/src/Microsoft.TemplateEngine.Utils/CacheTag.cs index a4c37848c09..d822758d035 100644 --- a/src/Microsoft.TemplateEngine.Utils/CacheTag.cs +++ b/src/Microsoft.TemplateEngine.Utils/CacheTag.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/CombinedList.cs b/src/Microsoft.TemplateEngine.Utils/CombinedList.cs index 1e18d4bb063..c831e474829 100644 --- a/src/Microsoft.TemplateEngine.Utils/CombinedList.cs +++ b/src/Microsoft.TemplateEngine.Utils/CombinedList.cs @@ -1,9 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; namespace Microsoft.TemplateEngine.Utils { diff --git a/src/Microsoft.TemplateEngine.Utils/ContentGenerationException.cs b/src/Microsoft.TemplateEngine.Utils/ContentGenerationException.cs index 191d6b35a24..a16c52e5ac3 100644 --- a/src/Microsoft.TemplateEngine.Utils/ContentGenerationException.cs +++ b/src/Microsoft.TemplateEngine.Utils/ContentGenerationException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Utils { public class ContentGenerationException : Exception diff --git a/src/Microsoft.TemplateEngine.Utils/DefaultTemplateEngineHost.cs b/src/Microsoft.TemplateEngine.Utils/DefaultTemplateEngineHost.cs index 3caf49c50b2..cc425e3a8da 100644 --- a/src/Microsoft.TemplateEngine.Utils/DefaultTemplateEngineHost.cs +++ b/src/Microsoft.TemplateEngine.Utils/DefaultTemplateEngineHost.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.TemplateEngine.Abstractions; @@ -13,12 +11,10 @@ namespace Microsoft.TemplateEngine.Utils [Obsolete("Use Microsoft.TemplateEngine.Edge.DefaultTemplateEngineHost instead.")] public class DefaultTemplateEngineHost : ITemplateEngineHost { - private static readonly IReadOnlyList<(Type Type, IIdentifiedComponent Instance)> NoComponents = Array.Empty<(Type Type, IIdentifiedComponent Instance)>(); + private static readonly IReadOnlyList<(Type Type, IIdentifiedComponent Instance)> NoComponents = []; private readonly IReadOnlyDictionary _hostDefaults; private readonly IReadOnlyList<(Type InterfaceType, IIdentifiedComponent Instance)> _hostBuiltInComponents; private readonly Dictionary> _diagnosticLoggers; - private readonly ILoggerFactory _loggerFactory; - private readonly ILogger _logger; public DefaultTemplateEngineHost(string hostIdentifier, string version) : this(hostIdentifier, version, null) @@ -49,8 +45,8 @@ public DefaultTemplateEngineHost(string hostIdentifier, string version, Dictiona _hostBuiltInComponents = builtIns ?? NoComponents; FallbackHostTemplateConfigNames = fallbackHostTemplateConfigNames ?? new List(); _diagnosticLoggers = new Dictionary>(); - _loggerFactory = NullLoggerFactory.Instance; - _logger = _loggerFactory.CreateLogger("Template Engine") ?? NullLogger.Instance; + LoggerFactory = NullLoggerFactory.Instance; + Logger = LoggerFactory.CreateLogger("Template Engine"); } public IPhysicalFileSystem FileSystem { get; private set; } @@ -65,9 +61,9 @@ public DefaultTemplateEngineHost(string hostIdentifier, string version, Dictiona public virtual IReadOnlyList<(Type InterfaceType, IIdentifiedComponent Instance)> BuiltInComponents => _hostBuiltInComponents; - public ILogger Logger => _logger; + public ILogger Logger { get; } - public ILoggerFactory LoggerFactory => _loggerFactory; + public ILoggerFactory LoggerFactory { get; } public virtual void LogMessage(string message) { @@ -144,7 +140,7 @@ public void LogTiming(string label, TimeSpan duration, int depth) public void Dispose() { - _loggerFactory?.Dispose(); + LoggerFactory?.Dispose(); } } } diff --git a/src/Microsoft.TemplateEngine.Utils/DefaultTemplatePackageProvider.cs b/src/Microsoft.TemplateEngine.Utils/DefaultTemplatePackageProvider.cs index a830ea72bcc..f21ce9a6040 100644 --- a/src/Microsoft.TemplateEngine.Utils/DefaultTemplatePackageProvider.cs +++ b/src/Microsoft.TemplateEngine.Utils/DefaultTemplatePackageProvider.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; @@ -24,8 +19,8 @@ public DefaultTemplatePackageProvider(ITemplatePackageProviderFactory factory, I { Factory = factory; _environmentSettings = environmentSettings; - _nupkgs = nupkgs ?? Array.Empty(); - _folders = folders ?? Array.Empty(); + _nupkgs = nupkgs ?? []; + _folders = folders ?? []; } public event Action? TemplatePackagesChanged; @@ -39,8 +34,8 @@ public DefaultTemplatePackageProvider(ITemplatePackageProviderFactory factory, I /// List of folders. public void UpdatePackages(IEnumerable? nupkgs = null, IEnumerable? folders = null) { - _nupkgs = nupkgs ?? Array.Empty(); - _folders = folders ?? Array.Empty(); + _nupkgs = nupkgs ?? []; + _folders = folders ?? []; TemplatePackagesChanged?.Invoke(); } diff --git a/src/Microsoft.TemplateEngine.Utils/DictionaryExtensions.cs b/src/Microsoft.TemplateEngine.Utils/DictionaryExtensions.cs index 1da54a94023..77b1e945c5a 100644 --- a/src/Microsoft.TemplateEngine.Utils/DictionaryExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/DictionaryExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Utils { public static class DictionaryExtensions diff --git a/src/Microsoft.TemplateEngine.Utils/DirectedGraph.cs b/src/Microsoft.TemplateEngine.Utils/DirectedGraph.cs index 23fc1d7ed07..41e5020f4ec 100644 --- a/src/Microsoft.TemplateEngine.Utils/DirectedGraph.cs +++ b/src/Microsoft.TemplateEngine.Utils/DirectedGraph.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.TemplateEngine.Utils { public class DirectedGraph @@ -12,7 +8,7 @@ public class DirectedGraph private static readonly DirectedGraph Empty = new(new Dictionary>()); private readonly Dictionary> _dependenciesMap; - private readonly Lazy>> _dependantsMap; + private readonly Lazy>> _dependentsMap; private readonly IReadOnlyList _vertices; /// @@ -23,7 +19,7 @@ public DirectedGraph(Dictionary> dependenciesMap) { _dependenciesMap = DeepCopy(dependenciesMap); _vertices = GetVertices(_dependenciesMap); - _dependantsMap = new Lazy>>(() => GetDependandsMap(_dependenciesMap, _vertices)); + _dependentsMap = new Lazy>>(() => GetDependentsMap(_dependenciesMap, _vertices)); } internal IReadOnlyDictionary> DependenciesMap => _dependenciesMap; @@ -54,18 +50,18 @@ public bool TryGetTopologicalSort(out IReadOnlyList sortedElements) } Queue noDependenciesQueue = new(inDegreeLookup.Where(kp => kp.Value == 0).Select(kp => kp.Key)); - var dependantsMap = _dependantsMap.Value; + var dependentsMap = _dependentsMap.Value; while (noDependenciesQueue.Count != 0) { T item = noDependenciesQueue.Dequeue(); result.Add(item); - foreach (T dependant in dependantsMap[item]) + foreach (T dependent in dependentsMap[item]) { - if (--inDegreeLookup[dependant] == 0) + if (--inDegreeLookup[dependent] == 0) { - noDependenciesQueue.Enqueue(dependant); + noDependenciesQueue.Enqueue(dependent); } } } @@ -74,10 +70,10 @@ public bool TryGetTopologicalSort(out IReadOnlyList sortedElements) return result.Count == _vertices.Count; } - public IEnumerable GetDependands(IEnumerable vertices) + public IEnumerable GetDependents(IEnumerable vertices) { - var dependantsMap = _dependantsMap.Value; - return vertices.Select(v => dependantsMap[v]).SelectMany(v => v); + var dependentsMap = _dependentsMap.Value; + return vertices.Select(v => dependentsMap[v]).SelectMany(v => v); } /// @@ -90,7 +86,7 @@ public IEnumerable GetDependands(IEnumerable vertices) /// If set to false, (some of) the given nodes may still be part of output graph, in case they transitively depend on any node from input set. /// /// - public DirectedGraph GetSubGraphDependandOnVertices(IReadOnlyList vertices, bool includeSeedVertices = false) + public DirectedGraph GetSubGraphDependentOnVertices(IReadOnlyList vertices, bool includeSeedVertices = false) { // Short circuit for empty graphs if (IsEmpty || vertices.Count == 0) @@ -98,21 +94,21 @@ public DirectedGraph GetSubGraphDependandOnVertices(IReadOnlyList vertices return Empty; } - HashSet dependantVertices = includeSeedVertices ? new HashSet(vertices) : new HashSet(); - Queue directDependants = new(vertices); - var dependantsMap = _dependantsMap.Value; + HashSet dependentVertices = includeSeedVertices ? new HashSet(vertices) : new HashSet(); + Queue directDependents = new(vertices); + var dependentsMap = _dependentsMap.Value; - while (directDependants.Count > 0) + while (directDependents.Count > 0) { - T parent = directDependants.Dequeue(); - if (dependantsMap.ContainsKey(parent)) + T parent = directDependents.Dequeue(); + if (dependentsMap.ContainsKey(parent)) { - directDependants.AddRange(dependantsMap[parent].Where(dependantVertices.Add)); + directDependents.AddRange(dependentsMap[parent].Where(dependentVertices.Add)); } } - return _dependenciesMap.Where(p => dependantVertices.Contains(p.Key)) - .ToDictionary(p => p.Key, p => new HashSet(p.Value.Where(dependantVertices.Contains))); + return _dependenciesMap.Where(p => dependentVertices.Contains(p.Key)) + .ToDictionary(p => p.Key, p => new HashSet(p.Value.Where(dependentVertices.Contains))); } /// @@ -148,18 +144,18 @@ public bool HasCycle(out IReadOnlyList cycle) private static IReadOnlyList GetVertices(Dictionary> dependenciesMap) => dependenciesMap.Keys.Union(dependenciesMap.Values.SelectMany(v => v)).Distinct().ToList(); - private static Dictionary> GetDependandsMap(Dictionary> dependenciesMap, IReadOnlyList vertices) + private static Dictionary> GetDependentsMap(Dictionary> dependenciesMap, IReadOnlyList vertices) { - var dependantsMap = vertices.ToDictionary(v => v, v => new HashSet()); + var dependentsMap = vertices.ToDictionary(v => v, v => new HashSet()); foreach (KeyValuePair> keyValuePair in dependenciesMap) { foreach (T dependency in keyValuePair.Value!) { - _ = dependantsMap[dependency].Add(keyValuePair.Key); + _ = dependentsMap[dependency].Add(keyValuePair.Key); } } - return dependantsMap; + return dependentsMap; } private static Dictionary> DeepCopy(Dictionary> dependenciesMap) diff --git a/src/Microsoft.TemplateEngine.Utils/EngineEnvironmentSettingsExtensions.cs b/src/Microsoft.TemplateEngine.Utils/EngineEnvironmentSettingsExtensions.cs index 1663ff479c7..f951e710c1a 100644 --- a/src/Microsoft.TemplateEngine.Utils/EngineEnvironmentSettingsExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/EngineEnvironmentSettingsExtensions.cs @@ -9,7 +9,7 @@ namespace Microsoft.TemplateEngine.Utils public static class EngineEnvironmentSettingsExtensions { /// - /// Tries to mount a from specified . + /// Tries to mount a from specified . /// Using all in . /// /// diff --git a/src/Microsoft.TemplateEngine.Utils/EngineInitializationException.cs b/src/Microsoft.TemplateEngine.Utils/EngineInitializationException.cs index 0387aaf0bd8..43fb97010aa 100644 --- a/src/Microsoft.TemplateEngine.Utils/EngineInitializationException.cs +++ b/src/Microsoft.TemplateEngine.Utils/EngineInitializationException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Utils { public class EngineInitializationException : Exception diff --git a/src/Microsoft.TemplateEngine.Utils/EnumerableExtensions.cs b/src/Microsoft.TemplateEngine.Utils/EnumerableExtensions.cs index 06800d21da3..7bb2193b752 100644 --- a/src/Microsoft.TemplateEngine.Utils/EnumerableExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/EnumerableExtensions.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.TemplateEngine.Utils { public static class EnumerableExtensions diff --git a/src/Microsoft.TemplateEngine.Utils/EqualityExtensions.cs b/src/Microsoft.TemplateEngine.Utils/EqualityExtensions.cs index e888c540585..8280a58bc33 100644 --- a/src/Microsoft.TemplateEngine.Utils/EqualityExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/EqualityExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - namespace Microsoft.TemplateEngine.Utils { public static class EqualityExtensions @@ -27,27 +24,25 @@ public static bool AllAreTheSame(this IEnumerable items, Func.Default.Equals; - using (IEnumerator enumerator = items.GetEnumerator()) + using IEnumerator enumerator = items.GetEnumerator(); + if (!enumerator.MoveNext()) { - if (!enumerator.MoveNext()) - { - return true; //If there are no elements they're all the same - } + return true; //If there are no elements they're all the same + } - TValue? firstValue = selector(enumerator.Current); + TValue? firstValue = selector(enumerator.Current); - while (enumerator.MoveNext()) - { - TValue? currentValue = selector(enumerator.Current); + while (enumerator.MoveNext()) + { + TValue? currentValue = selector(enumerator.Current); - if (!comparer(firstValue, currentValue)) - { - return false; - } + if (!comparer(firstValue, currentValue)) + { + return false; } - - return true; } + + return true; } } } diff --git a/src/Microsoft.TemplateEngine.Utils/FileFindHelpers.cs b/src/Microsoft.TemplateEngine.Utils/FileFindHelpers.cs index 454d885e8a9..75e8bbec70d 100644 --- a/src/Microsoft.TemplateEngine.Utils/FileFindHelpers.cs +++ b/src/Microsoft.TemplateEngine.Utils/FileFindHelpers.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; namespace Microsoft.TemplateEngine.Utils @@ -19,9 +15,8 @@ public static IReadOnlyList FindFilesAtOrAbovePath(IPhysicalFileSystem f do { List filesInDir = fileSystem.EnumerateFileSystemEntries(directory, matchPattern, SearchOption.TopDirectoryOnly).ToList(); - List matches = new(); - matches = secondaryFilter == null ? filesInDir : filesInDir.Where(x => secondaryFilter(x)).ToList(); + List matches = secondaryFilter == null ? filesInDir : filesInDir.Where(x => secondaryFilter(x)).ToList(); if (matches.Count > 0) { diff --git a/src/Microsoft.TemplateEngine.Utils/FileSystemInfoExtensions.cs b/src/Microsoft.TemplateEngine.Utils/FileSystemInfoExtensions.cs index a936465202d..86f80011174 100644 --- a/src/Microsoft.TemplateEngine.Utils/FileSystemInfoExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/FileSystemInfoExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Utils @@ -16,12 +13,10 @@ public static void CopyTo(this IDirectory source, string target) foreach (IFile file in source.EnumerateFiles("*", SearchOption.TopDirectoryOnly)) { - using (Stream f = source.MountPoint.EnvironmentSettings.Host.FileSystem.CreateFile(Path.Combine(target, file.Name))) - using (Stream s = file.OpenRead()) - { - s.CopyTo(f); - f.Flush(); - } + using Stream f = source.MountPoint.EnvironmentSettings.Host.FileSystem.CreateFile(Path.Combine(target, file.Name)); + using Stream s = file.OpenRead(); + s.CopyTo(f); + f.Flush(); } foreach (IDirectory dir in source.EnumerateDirectories("*", SearchOption.TopDirectoryOnly)) diff --git a/src/Microsoft.TemplateEngine.Utils/Glob.cs b/src/Microsoft.TemplateEngine.Utils/Glob.cs index d5e556ae21b..95d33889103 100644 --- a/src/Microsoft.TemplateEngine.Utils/Glob.cs +++ b/src/Microsoft.TemplateEngine.Utils/Glob.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.TemplateEngine.Utils { public class Glob : IPatternMatcher @@ -240,7 +236,7 @@ private class ExactPathMatcher : IMatcher public bool CanConsume(string test, int startAt, out int endPosition) { - int nextSlash = test.IndexOf("/", startAt, StringComparison.Ordinal); + int nextSlash = test.IndexOf('/', startAt); if (nextSlash > -1) { diff --git a/src/Microsoft.TemplateEngine.Utils/IFileSystemInfoExtensions.cs b/src/Microsoft.TemplateEngine.Utils/IFileSystemInfoExtensions.cs index ef535f29546..62dac8f53f4 100644 --- a/src/Microsoft.TemplateEngine.Utils/IFileSystemInfoExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/IFileSystemInfoExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/IScanTemplateInfoExtensions.cs b/src/Microsoft.TemplateEngine.Utils/IScanTemplateInfoExtensions.cs index 604c61fca3d..c265d88b8d2 100644 --- a/src/Microsoft.TemplateEngine.Utils/IScanTemplateInfoExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/IScanTemplateInfoExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -15,7 +12,7 @@ public static class IScanTemplateInfoExtensions /// /// Converts to . /// - /// to converr. + /// to convert. /// the path to localization file to use in . /// the path to host config file to use in . public static ITemplateInfo ToITemplateInfo(this IScanTemplateInfo templateInfo, string? locFilePath = null, string? hostFilePath = null) => new LegacyTemplateInfo(templateInfo, locFilePath, hostFilePath); @@ -23,14 +20,12 @@ public static class IScanTemplateInfoExtensions private class LegacyTemplateInfo : ITemplateInfo { private readonly IScanTemplateInfo _templateInfo; - private readonly string? _locFilePath; - private readonly string? _hostFilePath; internal LegacyTemplateInfo(IScanTemplateInfo templateInfo, string? locFilePath = null, string? hostFilePath = null) { _templateInfo = templateInfo; - _locFilePath = locFilePath; - _hostFilePath = hostFilePath; + LocaleConfigPlace = locFilePath; + HostConfigPlace = hostFilePath; } public string? Author => _templateInfo.Author; @@ -73,9 +68,9 @@ internal LegacyTemplateInfo(IScanTemplateInfo templateInfo, string? locFilePath public string ConfigPlace => _templateInfo.ConfigPlace; - public string? LocaleConfigPlace => _locFilePath; + public string? LocaleConfigPlace { get; } - public string? HostConfigPlace => _hostFilePath; + public string? HostConfigPlace { get; } public string? ThirdPartyNotices => _templateInfo.ThirdPartyNotices; diff --git a/src/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs b/src/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs index c371ac72d57..fc1789d5402 100644 --- a/src/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs +++ b/src/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; using System.Text; using System.Text.RegularExpressions; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; @@ -429,11 +426,9 @@ public void FileCopy(string sourcePath, string targetPath, bool overwrite) throw new IOException($"File already exists {targetPath}"); } - using (Stream s = OpenRead(sourcePath)) - using (Stream t = CreateFile(targetPath)) - { - s.CopyTo(t); - } + using Stream s = OpenRead(sourcePath); + using Stream t = CreateFile(targetPath); + s.CopyTo(t); } public void FileDelete(string path) @@ -526,11 +521,9 @@ public Stream OpenRead(string path) public string ReadAllText(string path) { - using (Stream s = OpenRead(path)) - using (StreamReader r = new(s, Encoding.UTF8, true, 8192, true)) - { - return r.ReadToEnd(); - } + using Stream s = OpenRead(path); + using StreamReader r = new(s, Encoding.UTF8, true, 8192, true); + return r.ReadToEnd(); } public byte[] ReadAllBytes(string path) @@ -539,22 +532,18 @@ public byte[] ReadAllBytes(string path) using Stream s = OpenRead(path); if (s is not MemoryStream ms) { - using (MemoryStream stream = new()) - { - s.CopyTo(stream); - return stream.ToArray(); - } + using MemoryStream stream = new(); + s.CopyTo(stream); + return stream.ToArray(); } return ms.ToArray(); } public void WriteAllText(string path, string value) { - using (Stream s = CreateFile(path)) - using (StreamWriter r = new(s, Encoding.UTF8, 8192, true)) - { - r.Write(value); - } + using Stream s = CreateFile(path); + using StreamWriter r = new(s, Encoding.UTF8, 8192, true); + r.Write(value); } public FileAttributes GetFileAttributes(string file) @@ -700,7 +689,7 @@ public string PathRelativeTo(string target, string relativeTo) /// Currently not implemented in . /// Just returns object, but never calls callback. /// - public IDisposable WatchFileChanges(string filepath, FileSystemEventHandler fileChanged) + public IDisposable WatchFileChanges(string filePath, FileSystemEventHandler fileChanged) { return new MemoryStream(); //Just some disposable dummy } @@ -791,7 +780,7 @@ public FileSystemFile(string name, string fullPath) { Name = name; FullPath = fullPath; - _data = Array.Empty(); + _data = []; } public string Name { get; } diff --git a/src/Microsoft.TemplateEngine.Utils/InstallRequestPathResolution.cs b/src/Microsoft.TemplateEngine.Utils/InstallRequestPathResolution.cs index 8d86c030f8c..56c5ec05af2 100644 --- a/src/Microsoft.TemplateEngine.Utils/InstallRequestPathResolution.cs +++ b/src/Microsoft.TemplateEngine.Utils/InstallRequestPathResolution.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/src/Microsoft.TemplateEngine.Utils/ListExtensions.cs b/src/Microsoft.TemplateEngine.Utils/ListExtensions.cs index 3e111e65cde..b9e2e52f057 100644 --- a/src/Microsoft.TemplateEngine.Utils/ListExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/ListExtensions.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; namespace Microsoft.TemplateEngine.Utils { @@ -50,14 +47,14 @@ public static class ListExtensions return allGrouped; } - private struct ValueWrapper + private readonly struct ValueWrapper { public ValueWrapper(T val) { Val = val; } - public T Val { get; private set; } + public T Val { get; } #pragma warning disable IDE0251 // Make member 'readonly' public override bool Equals(object obj) diff --git a/src/Microsoft.TemplateEngine.Utils/LocalizableStrings.Designer.cs b/src/Microsoft.TemplateEngine.Utils/LocalizableStrings.Designer.cs deleted file mode 100644 index b1e64b48599..00000000000 --- a/src/Microsoft.TemplateEngine.Utils/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,72 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Utils { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Utils.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Key [{0}] is already present.. - /// - internal static string DictionaryExtensions_Error_KeyExists { - get { - return ResourceManager.GetString("DictionaryExtensions_Error_KeyExists", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.TemplateEngine.Utils/LocalizationLocator.cs b/src/Microsoft.TemplateEngine.Utils/LocalizationLocator.cs index 5aa76b200bc..e5d0ac96615 100644 --- a/src/Microsoft.TemplateEngine.Utils/LocalizationLocator.cs +++ b/src/Microsoft.TemplateEngine.Utils/LocalizationLocator.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils @@ -41,7 +39,7 @@ public LocalizationLocator( public IReadOnlyDictionary ParameterSymbols { get; } - IReadOnlyList IValidationInfo.ValidationErrors => Array.Empty(); + IReadOnlyList IValidationInfo.ValidationErrors => []; bool IValidationInfo.IsValid => true; } diff --git a/src/Microsoft.TemplateEngine.Utils/Microsoft.TemplateEngine.Utils.csproj b/src/Microsoft.TemplateEngine.Utils/Microsoft.TemplateEngine.Utils.csproj index ecdb31b5e2d..8ca4128f300 100644 --- a/src/Microsoft.TemplateEngine.Utils/Microsoft.TemplateEngine.Utils.csproj +++ b/src/Microsoft.TemplateEngine.Utils/Microsoft.TemplateEngine.Utils.csproj @@ -1,13 +1,19 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) Components used by all Template Engine extensions and consumers true true true + + + + annotations + + @@ -19,21 +25,12 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + + diff --git a/src/Microsoft.TemplateEngine.Utils/MultiValueParameter.cs b/src/Microsoft.TemplateEngine.Utils/MultiValueParameter.cs index 92c8668d757..99d3fb9e9cd 100644 --- a/src/Microsoft.TemplateEngine.Utils/MultiValueParameter.cs +++ b/src/Microsoft.TemplateEngine.Utils/MultiValueParameter.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.TemplateEngine.Utils { /// @@ -34,7 +30,7 @@ public MultiValueParameter(IReadOnlyList values) /// /// The actual atomic values specified for the parameter. /// - public IReadOnlyList Values { get; private init; } + public IReadOnlyList Values { get; } public static bool TryPerformMultiValueEqual(object x, object y, out bool result) { @@ -50,7 +46,7 @@ public static bool TryPerformMultiValueEqual(object x, object y, out bool result { if (x is MultiValueParameter mv && y is string sv) { - result = MultivalueEquals(mv, sv); + result = MultiValueEquals(mv, sv); return true; } } @@ -58,7 +54,7 @@ public static bool TryPerformMultiValueEqual(object x, object y, out bool result { if (y is MultiValueParameter mv && x is string sv) { - result = MultivalueEquals(mv, sv); + result = MultiValueEquals(mv, sv); return true; } } @@ -98,7 +94,7 @@ protected bool Equals(MultiValueParameter other) return set1.SetEquals(set2); } - private static bool MultivalueEquals(MultiValueParameter mv, string comparand) + private static bool MultiValueEquals(MultiValueParameter mv, string comparand) { foreach (string s in mv.Values) { diff --git a/src/Microsoft.TemplateEngine.Utils/ParameterSetDataExtensions.cs b/src/Microsoft.TemplateEngine.Utils/ParameterSetDataExtensions.cs index 4f558409a5e..6062cfae6cb 100644 --- a/src/Microsoft.TemplateEngine.Utils/ParameterSetDataExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/ParameterSetDataExtensions.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Parameters; @@ -14,7 +11,7 @@ public static class ParameterSetDataExtensions /// /// Creates instance of from the legacy . /// - /// Legacy parameterset to be converted. + /// Legacy parameter set to be converted. /// [Obsolete("IParameterSet should not be used - it is replaced with IParameterSetData", false)] public static IParameterSetData ToParameterSetData(this IParameterSet parameterSet) diff --git a/src/Microsoft.TemplateEngine.Utils/ParserExtensions.cs b/src/Microsoft.TemplateEngine.Utils/ParserExtensions.cs index ab2465b084a..e049b07dcd1 100644 --- a/src/Microsoft.TemplateEngine.Utils/ParserExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/ParserExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Globalization; namespace Microsoft.TemplateEngine.Utils @@ -17,7 +16,7 @@ public static class ParserExtensions /// true when can be parsed in current or invariant culture. /// false when cannot be parsed in current or invariant culture. /// - public static bool DoubleTryParseСurrentOrInvariant(string? stringValue, out double doubleValue) + public static bool DoubleTryParseCurrentOrInvariant(string? stringValue, out double doubleValue) { if (double.TryParse(stringValue, NumberStyles.Float, CultureInfo.CurrentCulture, out doubleValue)) { diff --git a/src/Microsoft.TemplateEngine.Utils/PhysicalFileSystem.cs b/src/Microsoft.TemplateEngine.Utils/PhysicalFileSystem.cs index ab502adbf54..28667dc8f29 100644 --- a/src/Microsoft.TemplateEngine.Utils/PhysicalFileSystem.cs +++ b/src/Microsoft.TemplateEngine.Utils/PhysicalFileSystem.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; namespace Microsoft.TemplateEngine.Utils @@ -126,9 +123,9 @@ public string PathRelativeTo(string target, string relativeTo) return resultPath; } - public IDisposable WatchFileChanges(string filepath, FileSystemEventHandler fileChanged) + public IDisposable WatchFileChanges(string filePath, FileSystemEventHandler fileChanged) { - FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(filepath), Path.GetFileName(filepath)); + FileSystemWatcher watcher = new FileSystemWatcher(Path.GetDirectoryName(filePath), Path.GetFileName(filePath)); watcher.Changed += fileChanged; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.EnableRaisingEvents = true; diff --git a/src/Microsoft.TemplateEngine.Utils/PublicAPI.Shipped.txt b/src/Microsoft.TemplateEngine.Utils/PublicAPI.Shipped.txt index e33ca4ff0f9..77c0d61c507 100644 --- a/src/Microsoft.TemplateEngine.Utils/PublicAPI.Shipped.txt +++ b/src/Microsoft.TemplateEngine.Utils/PublicAPI.Shipped.txt @@ -64,7 +64,7 @@ Microsoft.TemplateEngine.Utils.InMemoryFileSystem.ReadAllBytes(string! path) -> Microsoft.TemplateEngine.Utils.InMemoryFileSystem.ReadAllText(string! path) -> string! Microsoft.TemplateEngine.Utils.InMemoryFileSystem.SetFileAttributes(string! file, System.IO.FileAttributes attributes) -> void Microsoft.TemplateEngine.Utils.InMemoryFileSystem.SetLastWriteTimeUtc(string! file, System.DateTime lastWriteTimeUtc) -> void -Microsoft.TemplateEngine.Utils.InMemoryFileSystem.WatchFileChanges(string! filepath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! +Microsoft.TemplateEngine.Utils.InMemoryFileSystem.WatchFileChanges(string! filePath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! Microsoft.TemplateEngine.Utils.InMemoryFileSystem.WriteAllText(string! path, string! value) -> void Microsoft.TemplateEngine.Utils.InstallRequestPathResolution Microsoft.TemplateEngine.Utils.ListExtensions @@ -98,7 +98,7 @@ Microsoft.TemplateEngine.Utils.PhysicalFileSystem.ReadAllBytes(string! path) -> Microsoft.TemplateEngine.Utils.PhysicalFileSystem.ReadAllText(string! path) -> string! Microsoft.TemplateEngine.Utils.PhysicalFileSystem.SetFileAttributes(string! file, System.IO.FileAttributes attributes) -> void Microsoft.TemplateEngine.Utils.PhysicalFileSystem.SetLastWriteTimeUtc(string! file, System.DateTime lastWriteTimeUtc) -> void -Microsoft.TemplateEngine.Utils.PhysicalFileSystem.WatchFileChanges(string! filepath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! +Microsoft.TemplateEngine.Utils.PhysicalFileSystem.WatchFileChanges(string! filePath, System.IO.FileSystemEventHandler! fileChanged) -> System.IDisposable! Microsoft.TemplateEngine.Utils.PhysicalFileSystem.WriteAllText(string! path, string! value) -> void Microsoft.TemplateEngine.Utils.RangeVersionSpecification Microsoft.TemplateEngine.Utils.RangeVersionSpecification.IsEndInclusive.get -> bool @@ -196,8 +196,8 @@ Microsoft.TemplateEngine.Utils.DefaultTemplateEngineHost.Version.get -> string! Microsoft.TemplateEngine.Utils.DefaultTemplateEngineHost.VirtualizeDirectory(string! path) -> void Microsoft.TemplateEngine.Utils.DirectedGraph Microsoft.TemplateEngine.Utils.DirectedGraph.DirectedGraph(System.Collections.Generic.Dictionary!>! dependenciesMap) -> void -Microsoft.TemplateEngine.Utils.DirectedGraph.GetDependands(System.Collections.Generic.IEnumerable! vertices) -> System.Collections.Generic.IEnumerable! -Microsoft.TemplateEngine.Utils.DirectedGraph.GetSubGraphDependandOnVertices(System.Collections.Generic.IReadOnlyList! vertices, bool includeSeedVertices = false) -> Microsoft.TemplateEngine.Utils.DirectedGraph! +Microsoft.TemplateEngine.Utils.DirectedGraph.GetDependents(System.Collections.Generic.IEnumerable! vertices) -> System.Collections.Generic.IEnumerable! +Microsoft.TemplateEngine.Utils.DirectedGraph.GetSubGraphDependentOnVertices(System.Collections.Generic.IReadOnlyList! vertices, bool includeSeedVertices = false) -> Microsoft.TemplateEngine.Utils.DirectedGraph! Microsoft.TemplateEngine.Utils.DirectedGraph.HasCycle(out System.Collections.Generic.IReadOnlyList! cycle) -> bool Microsoft.TemplateEngine.Utils.DirectedGraph.TryGetTopologicalSort(out System.Collections.Generic.IReadOnlyList! sortedElements) -> bool Microsoft.TemplateEngine.Utils.EngineInitializationException.EngineInitializationException(string! message, string! settingsItem) -> void @@ -252,14 +252,14 @@ static Microsoft.TemplateEngine.Utils.MultiValueParameter.MultiValueSeparators.g static Microsoft.TemplateEngine.Utils.MultiValueParameter.TryPerformMultiValueEqual(object! x, object! y, out bool result) -> bool static Microsoft.TemplateEngine.Utils.ParameterSetDataExtensions.ToParameterSetData(this Microsoft.TemplateEngine.Abstractions.IParameterSet! parameterSet) -> Microsoft.TemplateEngine.Abstractions.Parameters.IParameterSetData! static Microsoft.TemplateEngine.Utils.ParserExtensions.ConvertToDoubleCurrentOrInvariant(object! value) -> double -static Microsoft.TemplateEngine.Utils.ParserExtensions.DoubleTryParseСurrentOrInvariant(string? stringValue, out double doubleValue) -> bool +static Microsoft.TemplateEngine.Utils.ParserExtensions.DoubleTryParseCurrentOrInvariant(string? stringValue, out double doubleValue) -> bool static Microsoft.TemplateEngine.Utils.RuntimeValueUtil.TryGetRuntimeValue(this Microsoft.TemplateEngine.Abstractions.IParameterSet! parameters, Microsoft.TemplateEngine.Abstractions.IEngineEnvironmentSettings! environmentSettings, string! name, out object? value, bool skipEnvironmentVariableSearch = false) -> bool static Microsoft.TemplateEngine.Utils.TemplateParameterExtensions.IsValidMultiValueParameterValue(this string! value) -> bool static Microsoft.TemplateEngine.Utils.TemplateParameterExtensions.TokenizeMultiValueParameter(this string! literal) -> System.Collections.Generic.IReadOnlyList! override Microsoft.TemplateEngine.Utils.RangeVersionSpecification.ToString() -> string! static Microsoft.TemplateEngine.Utils.Timing.Over(Microsoft.Extensions.Logging.ILogger! logger, string! label) -> Microsoft.TemplateEngine.Utils.Timing! -static Microsoft.TemplateEngine.Utils.VersionStringHelpers.CompareVersions(string! version1, string! version2) -> int? -static Microsoft.TemplateEngine.Utils.VersionStringHelpers.IsVersionWellFormed(string! version) -> bool +static Microsoft.TemplateEngine.Utils.VersionStringHelpers.CompareVersions(string? version1, string? version2) -> int? +static Microsoft.TemplateEngine.Utils.VersionStringHelpers.IsVersionWellFormed(string? version) -> bool static Microsoft.TemplateEngine.Utils.VersionStringHelpers.TryParseVersionSpecification(string! versionString, out Microsoft.TemplateEngine.Utils.IVersionSpecification? specification) -> bool static Microsoft.TemplateEngine.Utils.WellKnownSearchFilters.AuthorFilter(string? author) -> System.Func! static Microsoft.TemplateEngine.Utils.WellKnownSearchFilters.BaselineFilter(string? baselineName) -> System.Func! diff --git a/src/Microsoft.TemplateEngine.Utils/RuntimeValueUtils.cs b/src/Microsoft.TemplateEngine.Utils/RuntimeValueUtils.cs index e6a021c0776..6d09ea1cd68 100644 --- a/src/Microsoft.TemplateEngine.Utils/RuntimeValueUtils.cs +++ b/src/Microsoft.TemplateEngine.Utils/RuntimeValueUtils.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/TemplateAuthoringException.cs b/src/Microsoft.TemplateEngine.Utils/TemplateAuthoringException.cs index 648dae5a74a..aaaf0a08396 100644 --- a/src/Microsoft.TemplateEngine.Utils/TemplateAuthoringException.cs +++ b/src/Microsoft.TemplateEngine.Utils/TemplateAuthoringException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.Utils { public class TemplateAuthoringException : Exception diff --git a/src/Microsoft.TemplateEngine.Utils/TemplateInfoExtensions.cs b/src/Microsoft.TemplateEngine.Utils/TemplateInfoExtensions.cs index b3375e9701a..44220da524d 100644 --- a/src/Microsoft.TemplateEngine.Utils/TemplateInfoExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/TemplateInfoExtensions.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/TemplateMatchInfoExtensions.cs b/src/Microsoft.TemplateEngine.Utils/TemplateMatchInfoExtensions.cs index 409f04fd9b9..2a92cafe35d 100644 --- a/src/Microsoft.TemplateEngine.Utils/TemplateMatchInfoExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/TemplateMatchInfoExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; using Microsoft.TemplateEngine.Abstractions.TemplateFiltering; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/TemplateParameter.cs b/src/Microsoft.TemplateEngine.Utils/TemplateParameter.cs index 952b0a8a916..2f29c61383c 100644 --- a/src/Microsoft.TemplateEngine.Utils/TemplateParameter.cs +++ b/src/Microsoft.TemplateEngine.Utils/TemplateParameter.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/TemplateParameterExtensions.cs b/src/Microsoft.TemplateEngine.Utils/TemplateParameterExtensions.cs index abb6b5b7d52..b07518c44f0 100644 --- a/src/Microsoft.TemplateEngine.Utils/TemplateParameterExtensions.cs +++ b/src/Microsoft.TemplateEngine.Utils/TemplateParameterExtensions.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Utils diff --git a/src/Microsoft.TemplateEngine.Utils/Timing.cs b/src/Microsoft.TemplateEngine.Utils/Timing.cs index 9d736cf688e..6b96bcb9a0e 100644 --- a/src/Microsoft.TemplateEngine.Utils/Timing.cs +++ b/src/Microsoft.TemplateEngine.Utils/Timing.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Microsoft.Extensions.Logging; diff --git a/src/Microsoft.TemplateEngine.Utils/VersionStringHelpers.cs b/src/Microsoft.TemplateEngine.Utils/VersionStringHelpers.cs index 03fb0cc922f..45f43538b03 100644 --- a/src/Microsoft.TemplateEngine.Utils/VersionStringHelpers.cs +++ b/src/Microsoft.TemplateEngine.Utils/VersionStringHelpers.cs @@ -27,7 +27,7 @@ public static bool TryParseVersionSpecification(string versionString, out IVersi // -1 if version1 < version2 // 0 if version1 == version2 // 1 if version1 > version2 - public static int? CompareVersions(string version1, string version2) + public static int? CompareVersions(string? version1, string? version2) { if (!TryParseVersionString(version1, out int[]? parts1) || !TryParseVersionString(version2, out int[]? parts2)) { @@ -49,15 +49,15 @@ public static bool TryParseVersionSpecification(string versionString, out IVersi return 0; } - public static bool IsVersionWellFormed(string version) + public static bool IsVersionWellFormed(string? version) { return TryParseVersionString(version, out _); } - // tries to parse a version into 4 int parts, zero-padding on the rght if needed. + // tries to parse a version into 4 int parts, zero-padding on the right if needed. // more than 4 parts, return false. - // Unparse-able, return false. - private static bool TryParseVersionString(string version, out int[]? parsed) + // Not parse-able, return false. + private static bool TryParseVersionString(string? version, out int[]? parsed) { if (string.IsNullOrEmpty(version)) { @@ -65,16 +65,20 @@ private static bool TryParseVersionString(string version, out int[]? parsed) return false; } - string[] parts = version.Split(new[] { '.' }); - if (parts.Length is < 2 or > 4) + string[]? parts = version?.Split(new[] { '.' }); + + if (parts != null) { - parsed = null; - return false; + if (parts.Length is < 2 or > 4) + { + parsed = null; + return false; + } } parsed = new[] { 0, 0, 0, 0 }; - for (int i = 0; i < parts.Length; i++) + for (int i = 0; i < parts?.Length; i++) { if (int.TryParse(parts[i], out int intPart)) { diff --git a/src/Microsoft.TemplateEngine.Utils/WellKnownSearchFilters.cs b/src/Microsoft.TemplateEngine.Utils/WellKnownSearchFilters.cs index cd4c8130dd6..317a8a6f109 100644 --- a/src/Microsoft.TemplateEngine.Utils/WellKnownSearchFilters.cs +++ b/src/Microsoft.TemplateEngine.Utils/WellKnownSearchFilters.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.TemplateFiltering; @@ -225,7 +222,7 @@ public static class WellKnownSearchFilters } /// - /// Gets the list of template filters for template constraints defintion
+ /// Gets the list of template filters for template constraints definition
/// For each constraint the template filter will be created:
/// - if the constraint is not used in the template, does not add match disposition;
/// - if the template meets the constraint, adds match disposition with ;
diff --git a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplatePackageInfo.cs b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplatePackageInfo.cs index 2b8107be1bf..2654dad250a 100644 --- a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplatePackageInfo.cs +++ b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplatePackageInfo.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Microsoft.TemplateSearch.Common.Abstractions { /// diff --git a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProvider.cs b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProvider.cs index 883b29ba157..94de7086bba 100644 --- a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProvider.cs +++ b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProvider.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateSearch.Common.Abstractions diff --git a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProviderFactory.cs b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProviderFactory.cs index bdeb4b1fc20..d22900297ba 100644 --- a/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProviderFactory.cs +++ b/src/Microsoft.TemplateSearch.Common/Abstractions/ITemplateSearchProviderFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateSearch.Common.Abstractions diff --git a/src/Microsoft.TemplateSearch.Common/Abstractions/TemplatePackageSearchData.cs b/src/Microsoft.TemplateSearch.Common/Abstractions/TemplatePackageSearchData.cs index ef6924f6a82..20f9b991107 100644 --- a/src/Microsoft.TemplateSearch.Common/Abstractions/TemplatePackageSearchData.cs +++ b/src/Microsoft.TemplateSearch.Common/Abstractions/TemplatePackageSearchData.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateSearch.Common.Abstractions; namespace Microsoft.TemplateSearch.Common @@ -11,6 +8,7 @@ namespace Microsoft.TemplateSearch.Common /// /// Template package searchable data. /// + [System.Diagnostics.DebuggerDisplay("{Name}@{Version}")] public partial class TemplatePackageSearchData : ITemplatePackageInfo { public TemplatePackageSearchData(ITemplatePackageInfo packInfo, IEnumerable templates, IDictionary? data = null) diff --git a/src/Microsoft.TemplateSearch.Common/Abstractions/TemplateSearchData.cs b/src/Microsoft.TemplateSearch.Common/Abstractions/TemplateSearchData.cs index 6a4724230a7..dfc64835845 100644 --- a/src/Microsoft.TemplateSearch.Common/Abstractions/TemplateSearchData.cs +++ b/src/Microsoft.TemplateSearch.Common/Abstractions/TemplateSearchData.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; using Microsoft.TemplateEngine.Abstractions.Parameters; diff --git a/src/Microsoft.TemplateSearch.Common/Components.cs b/src/Microsoft.TemplateSearch.Common/Components.cs index 5c65d072347..5967f04c4c3 100644 --- a/src/Microsoft.TemplateSearch.Common/Components.cs +++ b/src/Microsoft.TemplateSearch.Common/Components.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateSearch.Common.Abstractions; using Microsoft.TemplateSearch.Common.Providers; diff --git a/src/Microsoft.TemplateSearch.Common/LocalizableStrings.Designer.cs b/src/Microsoft.TemplateSearch.Common/LocalizableStrings.Designer.cs deleted file mode 100644 index 4852798e9e0..00000000000 --- a/src/Microsoft.TemplateSearch.Common/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,108 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateSearch.Common { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateSearch.Common.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Failed to update search cache.. - /// - internal static string BlobStoreSourceFileProvider_Exception_FailedToUpdateCache { - get { - return ResourceManager.GetString("BlobStoreSourceFileProvider_Exception_FailedToUpdateCache", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Local search cache '{0}' does not exist.. - /// - internal static string BlobStoreSourceFileProvider_Exception_LocalCacheDoesNotExist { - get { - return ResourceManager.GetString("BlobStoreSourceFileProvider_Exception_LocalCacheDoesNotExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to update search cache. Local search cache will be used instead.. - /// - internal static string BlobStoreSourceFileProvider_Warning_LocalCacheWillBeUsed { - get { - return ResourceManager.GetString("BlobStoreSourceFileProvider_Warning_LocalCacheWillBeUsed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template search cache data is not supported.. - /// - internal static string TemplateSearchCache_Exception_NotSupported { - get { - return ResourceManager.GetString("TemplateSearchCache_Exception_NotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The template search cache data is not valid.. - /// - internal static string TemplateSearchCache_Exception_NotValid { - get { - return ResourceManager.GetString("TemplateSearchCache_Exception_NotValid", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.TemplateSearch.Common/Microsoft.TemplateSearch.Common.csproj b/src/Microsoft.TemplateSearch.Common/Microsoft.TemplateSearch.Common.csproj index 460e6d15cff..8e5c9cfec83 100644 --- a/src/Microsoft.TemplateSearch.Common/Microsoft.TemplateSearch.Common.csproj +++ b/src/Microsoft.TemplateSearch.Common/Microsoft.TemplateSearch.Common.csproj @@ -1,12 +1,19 @@ + - $(NETStandardTargetFramework) + $(NetCurrent);$(NetFrameworkCurrent) Components used by the template discovery tool, and also used for related functionality in the CLI. true true true + + + + annotations + + @@ -17,18 +24,8 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + @@ -37,4 +34,9 @@ + + + + + diff --git a/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProvider.cs b/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProvider.cs index 9d4e5bd181b..020c561249b 100644 --- a/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProvider.cs +++ b/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProvider.cs @@ -1,15 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Net; +#if NETFRAMEWORK using System.Net.Http; +#endif using System.Text; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine; using Microsoft.TemplateEngine.Abstractions; @@ -50,7 +46,7 @@ internal NuGetMetadataSearchProvider( } /// - /// Test constructor allowing override search cache uris. + /// Test constructor allowing override search cache Uris. /// internal NuGetMetadataSearchProvider( ITemplateSearchProviderFactory factory, @@ -178,40 +174,40 @@ private async Task AcquireFileFromCloudAsync(string searchMetadataFileLocation, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, CheckCertificateRevocationList = true }; - using (HttpClient client = new(handler)) + using HttpClient client = new(handler); + string etagFileLocation = searchMetadataFileLocation + ETagFileSuffix; + if (_environmentSettings.Host.FileSystem.FileExists(etagFileLocation)) { - string etagFileLocation = searchMetadataFileLocation + ETagFileSuffix; - if (_environmentSettings.Host.FileSystem.FileExists(etagFileLocation)) - { - string etagValue = _environmentSettings.Host.FileSystem.ReadAllText(etagFileLocation); - client.DefaultRequestHeaders.Add(IfNoneMatchHeaderName, $"\"{etagValue}\""); - } - client.DefaultRequestHeaders.Add(IfNoneMatchHeaderName, string.Empty); - using (HttpResponseMessage response = await client.GetAsync(searchMetadataUri, cancellationToken).ConfigureAwait(false)) + string etagValue = _environmentSettings.Host.FileSystem.ReadAllText(etagFileLocation); + client.DefaultRequestHeaders.Add(IfNoneMatchHeaderName, $"\"{etagValue}\""); + } + client.DefaultRequestHeaders.Add(IfNoneMatchHeaderName, string.Empty); + using HttpResponseMessage response = await client.GetAsync(searchMetadataUri, cancellationToken).ConfigureAwait(false); + _logger.LogDebug(GetResponseDetails(response)); + if (response.IsSuccessStatusCode) + { +#if NET + string resultText = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); +#else + string resultText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); +#endif + _environmentSettings.Host.FileSystem.WriteAllText(searchMetadataFileLocation, resultText); + _logger.LogDebug("Search cache file was successfully downloaded to {0}.", searchMetadataFileLocation); + if (response.Headers.TryGetValues(ETagHeaderName, out IEnumerable etagValues)) { - _logger.LogDebug(GetResponseDetails(response)); - if (response.IsSuccessStatusCode) + if (etagValues.Count() == 1) { - string resultText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - _environmentSettings.Host.FileSystem.WriteAllText(searchMetadataFileLocation, resultText); - _logger.LogDebug("Search cache file was successfully downloaded to {0}.", searchMetadataFileLocation); - if (response.Headers.TryGetValues(ETagHeaderName, out IEnumerable etagValues)) - { - if (etagValues.Count() == 1) - { - _environmentSettings.Host.FileSystem.WriteAllText(etagFileLocation, etagValues.First()); - } - _logger.LogDebug("ETag {0} was written to {1}.", etagValues.First(), etagFileLocation); - } - return; - } - else if (response.StatusCode == HttpStatusCode.NotModified) - { - _logger.LogDebug("Search cache file is not modified, updating the last modified date to now."); - _environmentSettings.Host.FileSystem.SetLastWriteTimeUtc(searchMetadataFileLocation, DateTime.UtcNow); - return; + _environmentSettings.Host.FileSystem.WriteAllText(etagFileLocation, etagValues.First()); } + _logger.LogDebug("ETag {0} was written to {1}.", etagValues.First(), etagFileLocation); } + return; + } + else if (response.StatusCode == HttpStatusCode.NotModified) + { + _logger.LogDebug("Search cache file is not modified, updating the last modified date to now."); + _environmentSettings.Host.FileSystem.SetLastWriteTimeUtc(searchMetadataFileLocation, DateTime.UtcNow); + return; } } catch (TaskCanceledException) diff --git a/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProviderFactory.cs b/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProviderFactory.cs index c4b8da1c80e..bf1a5398a4e 100644 --- a/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProviderFactory.cs +++ b/src/Microsoft.TemplateSearch.Common/Providers/NuGetMetadataSearchProviderFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateSearch.Common.Abstractions; diff --git a/src/Microsoft.TemplateSearch.Common/SearchResult.cs b/src/Microsoft.TemplateSearch.Common/SearchResult.cs index b4b4645e28d..110a3a0e60a 100644 --- a/src/Microsoft.TemplateSearch.Common/SearchResult.cs +++ b/src/Microsoft.TemplateSearch.Common/SearchResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateSearch.Common.Abstractions; @@ -30,7 +28,7 @@ internal SearchResult( Provider = provider ?? throw new ArgumentNullException(nameof(provider)); Success = success; ErrorMessage = errorMessage; - SearchHits = success ? hits! : Array.Empty<(ITemplatePackageInfo, IReadOnlyList)>(); + SearchHits = success ? hits! : []; } /// diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/BlobStorageTemplateInfo.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/BlobStorageTemplateInfo.cs index 3a2804d95e2..bcd57461605 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/BlobStorageTemplateInfo.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/BlobStorageTemplateInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; @@ -43,7 +40,7 @@ public BlobStorageTemplateInfo(ITemplateInfo templateInfo) ShortNameList = templateInfo.ShortNameList; ParameterDefinitions = new ParameterDefinitionSet(templateInfo.ParameterDefinitions?.Select(p => new BlobTemplateParameter(p))); Author = templateInfo.Author; - Classifications = templateInfo.Classifications ?? Array.Empty(); + Classifications = templateInfo.Classifications ?? []; Description = templateInfo.Description; GroupIdentity = templateInfo.GroupIdentity; Precedence = templateInfo.Precedence; @@ -94,7 +91,7 @@ private BlobStorageTemplateInfo(string identity, string name, IEnumerable Classifications { get; private set; } = new List(); [JsonIgnore] - public string? DefaultName => throw new NotImplementedException(); + public string DefaultName => throw new NotImplementedException(); [JsonProperty] public string? Description { get; private set; } @@ -155,7 +152,7 @@ private BlobStorageTemplateInfo(string identity, string name, IEnumerable TagsCollection { get; private set; } = new Dictionary(); [JsonProperty] - public IReadOnlyList PostActions { get; private set; } = Array.Empty(); + public IReadOnlyList PostActions { get; private set; } = []; [JsonIgnore] IReadOnlyList ITemplateMetadata.Constraints => throw new NotImplementedException(); @@ -168,7 +165,7 @@ public static BlobStorageTemplateInfo FromJObject(JObject entry) ?? throw new ArgumentException($"{nameof(entry)} doesn't have {nameof(Name)} property.", nameof(entry)); JToken? shortNameToken = entry.Get(nameof(ShortNameList)); - IEnumerable shortNames = shortNameToken?.JTokenStringOrArrayToCollection(Array.Empty()) + IEnumerable shortNames = shortNameToken?.JTokenStringOrArrayToCollection([]) ?? throw new ArgumentException($"{nameof(entry)} doesn't have {nameof(ShortNameList)} property.", nameof(entry)); BlobStorageTemplateInfo info = new BlobStorageTemplateInfo(identity, name, shortNames) @@ -228,9 +225,9 @@ public static BlobStorageTemplateInfo FromJObject(JObject entry) { foreach (JToken item in parametersArray) { - if (item is JObject jobj) + if (item is JObject jObj) { - templateParameters.Add(new BlobTemplateParameter(jobj)); + templateParameters.Add(new BlobTemplateParameter(jObj)); } } readParameters = true; @@ -429,7 +426,7 @@ internal BlobTemplateParameter(JObject jObject) public string? DefaultValue { get; internal set; } [JsonIgnore] - string? ITemplateParameter.DisplayName => throw new NotImplementedException(); + string ITemplateParameter.DisplayName => throw new NotImplementedException(); [JsonProperty] public string? DefaultIfOptionWithoutValue { get; internal set; } @@ -439,7 +436,7 @@ internal BlobTemplateParameter(JObject jObject) [Obsolete] [JsonIgnore] - string? ITemplateParameter.Documentation => throw new NotImplementedException(); + string ITemplateParameter.Documentation => throw new NotImplementedException(); [JsonProperty] public bool AllowMultipleValues { get; internal set; } @@ -487,7 +484,7 @@ public BlobLegacyCacheTag(string? description, IReadOnlyDictionary throw new NotImplementedException(); + public string DisplayName => throw new NotImplementedException(); [JsonIgnore] public IReadOnlyDictionary Choices => throw new NotImplementedException(); @@ -517,7 +514,7 @@ public BlobLegacyCacheParameter(string? description, string? dataType, string? d public string? DefaultIfOptionWithoutValue { get; } [JsonIgnore] - public string? DisplayName => throw new NotImplementedException(); + public string DisplayName => throw new NotImplementedException(); } } diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/LegacySearchCacheReader.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/LegacySearchCacheReader.cs index 0fb6981238c..ee6c1acd6c8 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/LegacySearchCacheReader.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/LegacySearchCacheReader.cs @@ -1,11 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackInfo.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackInfo.cs index f243cbc43db..9d0c1f4d1a5 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackInfo.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateSearch.Common.Abstractions; using Newtonsoft.Json; @@ -37,7 +34,7 @@ internal PackInfo(string name, string version, long totalDownloads, IEnumerable< public long TotalDownloads { get; } [JsonProperty] - public IReadOnlyList Owners { get; } = Array.Empty(); + public IReadOnlyList Owners { get; } = []; [JsonProperty] public bool Reserved { get; } diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackToTemplateEntry.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackToTemplateEntry.cs index ac905a8b414..269095a0a45 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackToTemplateEntry.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/PackToTemplateEntry.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Newtonsoft.Json; namespace Microsoft.TemplateSearch.Common @@ -10,10 +8,10 @@ namespace Microsoft.TemplateSearch.Common [Obsolete("The class is deprecated. Use TemplateSearchCache instead to create search cache data.")] internal class PackToTemplateEntry { - internal PackToTemplateEntry(string version, List templateinfo) + internal PackToTemplateEntry(string version, List templateIdentificationEntry) { Version = version; - TemplateIdentificationEntry = templateinfo; + TemplateIdentificationEntry = templateIdentificationEntry; } [JsonProperty] @@ -23,7 +21,7 @@ internal PackToTemplateEntry(string version, List t internal long TotalDownloads { get; set; } [JsonProperty] - internal IReadOnlyList Owners { get; set; } = Array.Empty(); + internal IReadOnlyList Owners { get; set; } = []; [JsonProperty] internal bool Reserved { get; set; } diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateDiscoveryMetadata.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateDiscoveryMetadata.cs index d1fe167bde3..0fe64655b97 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateDiscoveryMetadata.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateDiscoveryMetadata.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateIdentificationEntry.cs b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateIdentificationEntry.cs index 29c71d7b000..c8e54773e18 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateIdentificationEntry.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateDiscoveryMetadata/TemplateIdentificationEntry.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Newtonsoft.Json; namespace Microsoft.TemplateSearch.Common diff --git a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplatePackageSearchData.Json.cs b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplatePackageSearchData.Json.cs index fef7823aa31..fb1a956737b 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplatePackageSearchData.Json.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplatePackageSearchData.Json.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine; using Newtonsoft.Json; @@ -30,7 +27,7 @@ internal TemplatePackageSearchData(JObject jObject, ILogger logger, IReadOnlyDic : throw new ArgumentException($"{nameof(jObject)} doesn't have {nameof(Name)} property or it is not a string.", nameof(jObject)); Version = jObject.ToString(nameof(Version)); TotalDownloads = jObject.ToInt32(nameof(TotalDownloads)); - Owners = jObject.Get(nameof(Owners)).JTokenStringOrArrayToCollection(Array.Empty()); + Owners = jObject.Get(nameof(Owners)).JTokenStringOrArrayToCollection([]); Reserved = jObject.ToBool(nameof(Reserved)); Description = jObject.ToString(nameof(Description)); diff --git a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.Json.cs b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.Json.cs index 6cb43c36884..ffea8ea8fbe 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.Json.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.Json.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine; using Newtonsoft.Json.Linq; diff --git a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.cs b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.cs index 62276b71d85..52de55a828c 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchCache.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Newtonsoft.Json; namespace Microsoft.TemplateSearch.Common @@ -12,12 +11,14 @@ internal partial class TemplateSearchCache internal TemplateSearchCache(IReadOnlyList data) { - TemplatePackages = data; + // when creating from freshly-generated data, order the results for clarity + TemplatePackages = data.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase).ToArray(); Version = CurrentVersion; } private TemplateSearchCache(IReadOnlyList data, string version) { + // don't order results when creating from a read file TemplatePackages = data; Version = version; } diff --git a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchData.Json.cs b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchData.Json.cs index a8e57c44cd4..1aa8a403e8d 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchData.Json.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateSearchCache/TemplateSearchData.Json.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Newtonsoft.Json; diff --git a/src/Microsoft.TemplateSearch.Common/TemplateSearchCoordinator.cs b/src/Microsoft.TemplateSearch.Common/TemplateSearchCoordinator.cs index 7051e6baa20..e35a76b2575 100644 --- a/src/Microsoft.TemplateSearch.Common/TemplateSearchCoordinator.cs +++ b/src/Microsoft.TemplateSearch.Common/TemplateSearchCoordinator.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateSearch.Common.Abstractions; @@ -17,7 +13,6 @@ namespace Microsoft.TemplateSearch.Common public sealed class TemplateSearchCoordinator { private readonly IEngineEnvironmentSettings _environmentSettings; - private readonly IReadOnlyDictionary> _additionalDataReaders; private readonly IReadOnlyDictionary _providers; public TemplateSearchCoordinator( @@ -25,11 +20,11 @@ public TemplateSearchCoordinator( IReadOnlyDictionary>? additionalDataReaders = null) { _environmentSettings = environmentSettings ?? throw new ArgumentNullException(nameof(environmentSettings)); - _additionalDataReaders = additionalDataReaders ?? new Dictionary>(); + IReadOnlyDictionary> additionalDataReaders1 = additionalDataReaders ?? new Dictionary>(); Dictionary configuredProviders = new Dictionary(); foreach (ITemplateSearchProviderFactory factory in _environmentSettings.Components.OfType()) { - configuredProviders.Add(factory.DisplayName, factory.CreateProvider(_environmentSettings, _additionalDataReaders)); + configuredProviders.Add(factory.DisplayName, factory.CreateProvider(_environmentSettings, additionalDataReaders1)); } _providers = configuredProviders; } diff --git a/src/Shared/IsExternalInit.cs b/src/Shared/IsExternalInit.cs index 403af298f91..5fb3b867834 100644 --- a/src/Shared/IsExternalInit.cs +++ b/src/Shared/IsExternalInit.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP2_0 || NETCOREAPP2_1 || NETCOREAPP2_2 || NETCOREAPP3_0 || NETCOREAPP3_1 || NET45 || NET451 || NET452 || NET6 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 +#if NETSTANDARD || NETFRAMEWORK using System.ComponentModel; @@ -13,9 +13,7 @@ namespace System.Runtime.CompilerServices /// This class should not be used by developers in source code. /// [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit - { - } + internal static class IsExternalInit; } #endif diff --git a/src/Shared/JExtensions.cs b/src/Shared/JExtensions.cs index 4e62ce7b9b3..4d5eff8db3f 100644 --- a/src/Shared/JExtensions.cs +++ b/src/Shared/JExtensions.cs @@ -1,12 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#if !NET6_0_OR_GREATER -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -#endif using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; @@ -157,7 +151,7 @@ internal static Guid ToGuid(this JToken token, string? key = null, Guid defaultV /// internal static IReadOnlyList ToStringReadOnlyList(this JObject jObject, string propertyName, IReadOnlyList? defaultValue = null) { - defaultValue ??= Array.Empty(); + defaultValue ??= []; JToken? token = jObject.Get(propertyName); if (token == null) { @@ -170,16 +164,16 @@ internal static IEnumerable PropertiesOf(this JToken? token, string? { if (token is not JObject obj) { - return Array.Empty(); + return []; } if (key != null) { if (!obj.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out JToken? element)) { - return Array.Empty(); + return []; } - return element is not JObject jObj ? Array.Empty() : jObj.Properties(); + return element is not JObject jObj ? [] : jObj.Properties(); } return obj.Properties(); } @@ -221,9 +215,9 @@ internal static IReadOnlyDictionary ToStringDictionary(this JTok /// Converts properties of to dictionary. /// Leaves the values as JToken. ///
- internal static IReadOnlyDictionary ToJTokenDictionary(this JToken token, StringComparer? comparaer = null, string? propertyName = null) + internal static IReadOnlyDictionary ToJTokenDictionary(this JToken token, StringComparer? comparer = null, string? propertyName = null) { - Dictionary result = new(comparaer ?? StringComparer.Ordinal); + Dictionary result = new(comparer ?? StringComparer.Ordinal); foreach (JProperty property in token.PropertiesOf(propertyName)) { @@ -237,9 +231,9 @@ internal static IReadOnlyDictionary ToJTokenDictionary(this JTok /// Converts properties of to dictionary. /// Values are serialized to string (as JToken). Strings are serialized as , i.e. needs to be parsed prior to be used. ///
- internal static IReadOnlyDictionary ToJTokenStringDictionary(this JToken token, StringComparer? comparaer = null, string? propertyName = null) + internal static IReadOnlyDictionary ToJTokenStringDictionary(this JToken token, StringComparer? comparer = null, string? propertyName = null) { - Dictionary result = new(comparaer ?? StringComparer.Ordinal); + Dictionary result = new(comparer ?? StringComparer.Ordinal); foreach (JProperty property in token.PropertiesOf(propertyName)) { @@ -273,7 +267,7 @@ internal static IReadOnlyList ArrayAsStrings(this JToken? token, string? if (token is not JArray arr) { - return Array.Empty(); + return []; } List values = new(); @@ -298,7 +292,7 @@ internal static IReadOnlyList ArrayAsGuids(this JToken? token, string? pro if (token is not JArray arr) { - return Array.Empty(); + return []; } List values = new(); diff --git a/template_feed/Microsoft.TemplateEngine.Authoring.Templates/Microsoft.TemplateEngine.Authoring.Templates.csproj b/template_feed/Microsoft.TemplateEngine.Authoring.Templates/Microsoft.TemplateEngine.Authoring.Templates.csproj index 0a7184dcc0d..0ecf01b3fe4 100644 --- a/template_feed/Microsoft.TemplateEngine.Authoring.Templates/Microsoft.TemplateEngine.Authoring.Templates.csproj +++ b/template_feed/Microsoft.TemplateEngine.Authoring.Templates/Microsoft.TemplateEngine.Authoring.Templates.csproj @@ -1,6 +1,7 @@  + - $(NETCoreTargetFramework) + $(NetCurrent) False False False @@ -10,7 +11,7 @@ true true true - 2008;NU5105 + $(NoWarn);2008;NU5105 true Microsoft.TemplateEngine.Authoring.Templates Microsoft @@ -19,12 +20,13 @@ https://github.com/dotnet/templating Template True - true + true + - content + diff --git a/template_feed/Microsoft.TemplateEngine.Authoring.Templates/content/TemplatePackage/New.Template.Package.csproj b/template_feed/Microsoft.TemplateEngine.Authoring.Templates/content/TemplatePackage/New.Template.Package.csproj index bc3240fc442..e078f5fe523 100644 --- a/template_feed/Microsoft.TemplateEngine.Authoring.Templates/content/TemplatePackage/New.Template.Package.csproj +++ b/template_feed/Microsoft.TemplateEngine.Authoring.Templates/content/TemplatePackage/New.Template.Package.csproj @@ -13,7 +13,7 @@ Template - net8.0 + net9.0 true false content diff --git a/test/Directory.Build.props b/test/Directory.Build.props index f330554d5e6..e4fe79a8347 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -1,8 +1,9 @@ - - + + - true + true + diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets deleted file mode 100644 index a562b95d8fc..00000000000 --- a/test/Directory.Build.targets +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandTests.cs b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandTests.cs index 5b14ed9c26b..01039bf238e 100644 --- a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandTests.cs +++ b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ExportCommandTests.cs @@ -53,7 +53,7 @@ public async Task LocFilesAreExportedFirstTime() catch (DirectoryNotFoundException) { // Since no templates were created, it is normal that no directory was created. - exportedFiles = Array.Empty(); + exportedFiles = []; } Assert.True(exportedFiles.Length > 0); Assert.All(exportedFiles, p => @@ -227,7 +227,7 @@ private static async Task RunTemplateLocalizer(string jsonContent, str catch (DirectoryNotFoundException) { // Since no templates were created, it is normal that no directory was created. - return Array.Empty(); + return []; } } diff --git a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests.csproj b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests.csproj index 30bf6b9ab78..257fabe0ffd 100644 --- a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests.csproj @@ -1,8 +1,7 @@ + - $(NETCoreTargetFramework) - false - enable + $(NetCurrent) @@ -21,5 +20,4 @@ - diff --git a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs index dcce55e0b82..33309dd6982 100644 --- a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs +++ b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/ValidateCommandTests.cs @@ -9,7 +9,6 @@ namespace Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests { - [UsesVerify] [Collection("Verify Tests")] public class ValidateCommandTests : TestBase { diff --git a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs index 7a8bad8be30..644cf2cddc2 100644 --- a/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs +++ b/test/Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests/VerifyCommandTests.cs @@ -10,7 +10,6 @@ namespace Microsoft.TemplateEngine.Authoring.CLI.IntegrationTests { - [UsesVerify] public class VerifyCommandTests : TestBase { private readonly ITestOutputHelper _log; @@ -132,7 +131,6 @@ public void VerifyCommandFullDevLoopWithNotInstalledTemplate() string templateOutputDir = templateShortName; //get the template location - string executingAssemblyPath = GetType().Assembly.Location; string templateLocation = Path.Combine(TestTemplatesLocation, "TestTemplate"); var cmd = new BasicCommand( diff --git a/test/Microsoft.TemplateEngine.Authoring.CLI.UnitTests/Microsoft.TemplateEngine.Authoring.CLI.UnitTests.csproj b/test/Microsoft.TemplateEngine.Authoring.CLI.UnitTests/Microsoft.TemplateEngine.Authoring.CLI.UnitTests.csproj index 2ae10c1846f..462969e7e66 100644 --- a/test/Microsoft.TemplateEngine.Authoring.CLI.UnitTests/Microsoft.TemplateEngine.Authoring.CLI.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.CLI.UnitTests/Microsoft.TemplateEngine.Authoring.CLI.UnitTests.csproj @@ -1,8 +1,7 @@ + - $(NETCoreTargetFramework) - false - enable + $(NetCurrent) @@ -13,5 +12,5 @@ - + diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests.csproj index 7db019170e8..a19dd0c75de 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests.csproj @@ -1,12 +1,11 @@ + - $(NETCoreTargetFramework) - enable + $(NetCurrent) + - - Always - + @@ -15,10 +14,6 @@ - - - - @@ -26,4 +21,5 @@ + diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/BasicTemplatePackage/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/BasicTemplatePackage/TemplatePackage.csproj index e35d3b09d26..de1d4d737e1 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/BasicTemplatePackage/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/BasicTemplatePackage/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage/TemplatePackage.csproj index e35d3b09d26..de1d4d737e1 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingName/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingName/TemplatePackage.csproj index e35d3b09d26..de1d4d737e1 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingName/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingName/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingOptionalData/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingOptionalData/TemplatePackage.csproj index e35d3b09d26..de1d4d737e1 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingOptionalData/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/InvalidTemplatePackage_MissingOptionalData/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackageEnDe/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackageEnDe/TemplatePackage.csproj index 245485f5ad9..7972c365944 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackageEnDe/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackageEnDe/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackagePartiallyLocalized/TemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackagePartiallyLocalized/TemplatePackage.csproj index 0bbb7b3b318..978d3321451 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackagePartiallyLocalized/TemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Tasks.IntegrationTests/Resources/TemplatePackagePartiallyLocalized/TemplatePackage.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 Template TemplatePackage Microsoft diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/ExampleTemplateTest.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/ExampleTemplateTest.cs index 84d45a7129a..7cf94a99bec 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/ExampleTemplateTest.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/ExampleTemplateTest.cs @@ -23,7 +23,7 @@ public ExampleTemplateTest(ITestOutputHelper log) // The identity of snapshots ilustrates that execution through API and through full blown command leads to identical results [Fact] - public async void VerificationEngineSampleDogfoodTest() + public async Task VerificationEngineSampleDogfoodTest() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string templateShortName = "TestAssets.SampleTestTemplate"; @@ -60,7 +60,7 @@ public async void VerificationEngineSampleDogfoodTest() } [Fact] - public async void VerificationEngineSampleDogfoodTest_ExecThroughApi() + public async Task VerificationEngineSampleDogfoodTest_ExecThroughApi() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string templateShortName = "TestAssets.SampleTestTemplate"; diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests.csproj b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests.csproj index fb87f5e96eb..889a18a0c9c 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests.csproj @@ -1,7 +1,7 @@ + - $(NETCoreTargetFramework) - enable + $(NetCurrent) diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.enableContactPage=true.verified/sample03/Program.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.enableContactPage=true.verified/sample03/Program.cs index 48647fceff0..e05e2ef4047 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.enableContactPage=true.verified/sample03/Program.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.enableContactPage=true.verified/sample03/Program.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.AspNetCore.Hosting; namespace sample03 diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.verified/sample03/Program.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.verified/sample03/Program.cs index 48647fceff0..e05e2ef4047 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.verified/sample03/Program.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/Snapshots/sample03.optional-page.verified/sample03/Program.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.AspNetCore.Hosting; namespace sample03 diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/TemplateEngineSamplesTest.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/TemplateEngineSamplesTest.cs index 49f53e230e9..8f8974ef3e8 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/TemplateEngineSamplesTest.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/TemplateEngineSamplesTest.cs @@ -35,10 +35,10 @@ public TemplateEngineSamplesTest(ITestOutputHelper log) [InlineData("13-constant-value", "sample13", null, "replacing of constant value")] [InlineData("15-computed-symbol", "sample15", null, "usage computed symbols")] [InlineData("16-string-value-transform", "sample16", null, "usage of derived parameter")] - public async void TemplateEngineSamplesProjectTest( + public async Task TemplateEngineSamplesProjectTest( string folderName, string shortName, - string[] args, + string[]? args, string caseDescription) { _log.LogInformation($"Template with {caseDescription}"); @@ -52,7 +52,7 @@ public async void TemplateEngineSamplesProjectTest( { TemplatePath = templateLocation, DoNotPrependCallerMethodNameToScenarioName = true, - ScenarioName = $"{folderName.Substring(folderName.IndexOf("-") + 1)}{argsScenarioName}" + ScenarioName = $"{folderName.Substring(folderName.IndexOf('-') + 1)}{argsScenarioName}" } .WithInstantiationThroughTemplateCreatorApi(templateArgs) .WithCustomScrubbers( @@ -65,7 +65,7 @@ public async void TemplateEngineSamplesProjectTest( private string GetSamplesTemplateLocation() => Path.Combine(CodeBaseRoot, "dotnet-template-samples", "content"); - private (Dictionary Args, string ArgsScenarioName) GetTemplateArgs(string[] args) + private (Dictionary Args, string ArgsScenarioName) GetTemplateArgs(string[]? args) { var templateArgs = new Dictionary(); StringBuilder sb = new StringBuilder(); diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/VerificationEngineTests.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/VerificationEngineTests.cs index 216b2b5bf7c..fd302f1ada2 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/VerificationEngineTests.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.IntegrationTests/VerificationEngineTests.cs @@ -18,7 +18,7 @@ public VerificationEngineTests(ITestOutputHelper log) } [Fact] - public async void VerificationEngineFullDevLoop() + public async Task VerificationEngineFullDevLoop() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string snapshotsDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); @@ -94,7 +94,7 @@ await executeTask2 } [Fact] - public async void VerificationEngineCustomVerifier() + public async Task VerificationEngineCustomVerifier() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string templateDir = "path with spaces"; @@ -146,7 +146,7 @@ await executeTask } [Fact] - public async void VerificationEngine_DotFile_EditorConfigTests() + public async Task VerificationEngine_DotFile_EditorConfigTests() { TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: "editorconfig") { @@ -160,7 +160,7 @@ public async void VerificationEngine_DotFile_EditorConfigTests() } [Fact] - public async void VerificationEngine_InstallsToCustomLocation_WithSettingsDirectorySpecified() + public async Task VerificationEngine_InstallsToCustomLocation_WithSettingsDirectorySpecified() { var settingsPath = TestUtils.CreateTemporaryFolder(); TemplateVerifierOptions options = new TemplateVerifierOptions(templateName: "editorconfig") diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests.csproj b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests.csproj index 51df7fbaa19..8383d627ded 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests.csproj @@ -1,7 +1,7 @@ + - $(NETCoreTargetFramework) - enable + $(NetCurrent) diff --git a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs index 2d127f5ead4..1ed796ab0c1 100644 --- a/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs +++ b/test/Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests/VerificationEngineTests.cs @@ -11,7 +11,6 @@ namespace Microsoft.TemplateEngine.Authoring.TemplateVerifier.UnitTests { - [UsesVerify] public class VerificationEngineTests { private readonly ILogger _log; @@ -22,7 +21,7 @@ public VerificationEngineTests(ITestOutputHelper log) } [Fact] - public async void CreateVerificationTaskWithCustomScrubbersAndVerifier() + public async Task CreateVerificationTaskWithCustomScrubbersAndVerifier() { string verifyLocation = "foo\\bar\\baz"; @@ -82,7 +81,7 @@ await VerificationEngine.CreateVerificationTask( } [Fact] - public async void ExecuteFailsOnInstantiationFailure() + public async Task ExecuteFailsOnInstantiationFailure() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string snapshotsDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); @@ -110,7 +109,7 @@ await executeTask } [Fact] - public async void ExecuteSucceedsOnExpectedInstantiationFailure() + public async Task ExecuteSucceedsOnExpectedInstantiationFailure() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string snapshotsDir = "Snapshots"; @@ -134,7 +133,7 @@ public async void ExecuteSucceedsOnExpectedInstantiationFailure() } [Fact] - public async void ExecuteSucceedsOnExpectedInstantiationSuccess() + public async Task ExecuteSucceedsOnExpectedInstantiationSuccess() { string workingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName().Replace(".", string.Empty)); string snapshotsDir = "Snapshots"; diff --git a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests.csproj b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests.csproj index 80acdd68896..a6c2777544c 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests.csproj @@ -1,9 +1,7 @@ - $(NETCoreTargetFramework) - enable - false + $(NetCurrent) diff --git a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.Basic.verified/templatepack/templatepack.csproj b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.Basic.verified/templatepack/templatepack.csproj index 38c483d8934..08378ee4649 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.Basic.verified/templatepack/templatepack.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.Basic.verified/templatepack/templatepack.csproj @@ -13,7 +13,7 @@ Template - net8.0 + net9.0 true false content diff --git a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.CLI.verified/templatepack/templatepack.csproj b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.CLI.verified/templatepack/templatepack.csproj index 38c483d8934..08378ee4649 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.CLI.verified/templatepack/templatepack.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.CLI.verified/templatepack/templatepack.csproj @@ -13,7 +13,7 @@ Template - net8.0 + net9.0 true false content diff --git a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.NoMSBuildTasks.verified/templatepack/templatepack.csproj b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.NoMSBuildTasks.verified/templatepack/templatepack.csproj index 5116334f22e..96855c9cf42 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.NoMSBuildTasks.verified/templatepack/templatepack.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.NoMSBuildTasks.verified/templatepack/templatepack.csproj @@ -13,7 +13,7 @@ Template - net8.0 + net9.0 true false content diff --git a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.WithName.verified/templatepack/MyTemplatePackage.csproj b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.WithName.verified/templatepack/MyTemplatePackage.csproj index cb4a7a26ef5..e2085ace761 100644 --- a/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.WithName.verified/templatepack/MyTemplatePackage.csproj +++ b/test/Microsoft.TemplateEngine.Authoring.Templates.IntegrationTests/Snapshots/templatepack.WithName.verified/templatepack/MyTemplatePackage.csproj @@ -13,7 +13,7 @@ Template - net8.0 + net9.0 true false content diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkMemoryStream.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkMemoryStream.cs new file mode 100644 index 00000000000..cd63e3eefbb --- /dev/null +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkMemoryStream.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.TemplateEngine.Core.UnitTests; + +internal class ChunkMemoryStream : MemoryStream +{ + private readonly int _chunkSize; + + internal ChunkMemoryStream(int chunkSize) + { + _chunkSize = chunkSize; + } + + internal ChunkMemoryStream(byte[] buffer, int chunkSize) : base(buffer) + { + _chunkSize = chunkSize; + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (count > _chunkSize) + { + count = _chunkSize; + } + return base.Read(buffer, offset, count); + } +} diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkStreamReadTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkStreamReadTests.cs index 152c76ca6f7..1697810aecd 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkStreamReadTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ChunkStreamReadTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; @@ -32,7 +30,7 @@ public void VerifyLongStreamNoReplacement() ChunkMemoryStream input = new ChunkMemoryStream(valueBytes, 512); ChunkMemoryStream output = new ChunkMemoryStream(1024); - IOperationProvider[] operations = Array.Empty(); + IOperationProvider[] operations = []; EngineConfig cfg = new EngineConfig(_engineEnvironmentSettings.Host.Logger, VariableCollection.Root()); IProcessor processor = Processor.Create(cfg, operations); @@ -132,40 +130,16 @@ public void VerifyConsumeWholeLine() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_engineEnvironmentSettings.Host.Logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream input = new ChunkMemoryStream(data, 1); Stream output = new ChunkMemoryStream(1); bool changed = processor.Run(input, output, 5); Verify(Encoding.UTF8, output, changed, "Hello \r\n There \r\n You", "Hello \r\n You"); } - - private class ChunkMemoryStream : MemoryStream - { - private readonly int _chunkSize; - - internal ChunkMemoryStream(int chunkSize) : base() - { - _chunkSize = chunkSize; - } - - internal ChunkMemoryStream(byte[] buffer, int chunkSize) : base(buffer) - { - _chunkSize = chunkSize; - } - - public override int Read(byte[] buffer, int offset, int count) - { - if (count > _chunkSize) - { - count = _chunkSize; - } - return base.Read(buffer, offset, count); - } - } } } diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/CombinedStreamTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/CombinedStreamTests.cs index 8caafa33a5b..012e9d0e238 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/CombinedStreamTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/CombinedStreamTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using Microsoft.TemplateEngine.Core.Util; using Xunit; @@ -50,29 +48,5 @@ public void CanReadStream(int requestedCount) Assert.Equal(0, read[i]); } } - - private class ChunkMemoryStream : MemoryStream - { - private readonly int _chunkSize; - - internal ChunkMemoryStream(int chunkSize) : base() - { - _chunkSize = chunkSize; - } - - internal ChunkMemoryStream(byte[] buffer, int chunkSize) : base(buffer) - { - _chunkSize = chunkSize; - } - - public override int Read(byte[] buffer, int offset, int count) - { - if (count > _chunkSize) - { - count = _chunkSize; - } - return base.Read(buffer, offset, count); - } - } } } diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/CommonOperationsTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/CommonOperationsTests.cs index 66f6dd9849a..db442812437 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/CommonOperationsTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/CommonOperationsTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Core.Contracts; @@ -32,11 +31,11 @@ public void VerifyTrimWhitespaceForward() return 0; }, true, - Encoding.UTF8.GetBytes("Hello")); + "Hello"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There"); + byte[] data = "Hello \r\n There"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -57,11 +56,11 @@ public void VerifyTrimWhitespaceBackward() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There"); + byte[] data = "Hello \r\n There"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -82,11 +81,11 @@ public void VerifyTrimWhitespaceBothDirections() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -107,11 +106,11 @@ public void VerifyTrimWhitespaceNeitherDirection() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -132,11 +131,11 @@ public void VerifyConsumeWholeLine() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -165,11 +164,11 @@ public void VerifyWhitespaceHandlerConsumeWholeLine(bool trim, bool trimForward, return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -194,11 +193,11 @@ public void VerifyWhitespaceHandlerTrim(bool trimForward, bool trimBackward) return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -220,11 +219,11 @@ public void VerifyWhitespaceHandlerTrimForwardButNotBack() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -245,11 +244,11 @@ public void VerifyWhitespaceHandlerTrimBackButNotForward() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); @@ -270,11 +269,11 @@ public void VerifyWhitespaceHandlerTrimBackAndForward() return 0; }, true, - Encoding.UTF8.GetBytes("There")); + "There"u8.ToArray()); EngineConfig cfg = new EngineConfig(_logger, new VariableCollection()); IProcessor processor = Processor.Create(cfg, o.Provider); - byte[] data = Encoding.UTF8.GetBytes("Hello \r\n There \r\n You"); + byte[] data = "Hello \r\n There \r\n You"u8.ToArray(); Stream d = new MemoryStream(data); MemoryStream result = new MemoryStream(); bool modified = processor.Run(d, result); diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs index 41e5611d9f9..ee8cd908c39 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.UncommentingBehavior.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.UncommentingBehavior.cs index 63f2c41792d..f974f042d26 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.UncommentingBehavior.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.UncommentingBehavior.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.VBStyleEvaluator.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.VBStyleEvaluator.cs index b2779273a4b..5d64fca95c9 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.VBStyleEvaluator.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.VBStyleEvaluator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.XmlBlockComments.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.XmlBlockComments.cs index ed4c62f11ea..e6ba784fac3 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.XmlBlockComments.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.XmlBlockComments.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/Cpp2EvaluatorTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/Cpp2EvaluatorTests.cs index e4a21382e51..2f686f99ef4 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/Cpp2EvaluatorTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/Cpp2EvaluatorTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Core.Expressions.Cpp2; using Microsoft.TemplateEngine.TestHelper; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/EncodingTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/EncodingTests.cs deleted file mode 100644 index 06841c13d52..00000000000 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/EncodingTests.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Microsoft.TemplateEngine.Core.UnitTests -{ - public class EncodingTests - { - } -} diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/LookaroundTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/LookaroundTests.cs index af4420c6602..cd7c9a9962f 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/LookaroundTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/LookaroundTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; @@ -188,7 +187,7 @@ public void TestReadAheadBreaksLookBehinds() IOperationProvider[] operations = { - new MockOperationProvider(new MockOperation(null, ReadaheadOneByte, true, Encoding.UTF8.GetBytes("foo"))), + new MockOperationProvider(new MockOperation(null, ReadaheadOneByte, true, "foo"u8.ToArray())), new Replacement("bar".TokenConfigBuilder().OnlyIfAfter("foot"), "b", null, true) }; EngineConfig cfg = new EngineConfig(_engineEnvironmentSettings.Host.Logger, VariableCollection.Root()); diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/Microsoft.TemplateEngine.Core.UnitTests.csproj b/test/Microsoft.TemplateEngine.Core.UnitTests/Microsoft.TemplateEngine.Core.UnitTests.csproj index 26a2cccdd99..24c1d04d700 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/Microsoft.TemplateEngine.Core.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/Microsoft.TemplateEngine.Core.UnitTests.csproj @@ -1,7 +1,7 @@ - + + - $(NETCoreTargetFramework);$(NETFullTargetFramework) - $(NETCoreTargetFramework) + $(NetCurrent);$(NetFrameworkCurrent) diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/OperationTrieTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/OperationTrieTests.cs index d0332dde179..ecc67a48cd5 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/OperationTrieTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/OperationTrieTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Matching; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/OrchestratorTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/OrchestratorTests.cs index 292461f4807..59f9d2d717f 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/OrchestratorTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/OrchestratorTests.cs @@ -25,7 +25,7 @@ public void VerifyRun() { Util.Orchestrator orchestrator = new Util.Orchestrator(_logger, new MockFileSystem()); MockMountPoint mnt = new MockMountPoint(_engineEnvironmentSettings); - mnt.MockRoot.AddDirectory("subdir").AddFile("test.file", System.Array.Empty()); + mnt.MockRoot.AddDirectory("subdir").AddFile("test.file", []); orchestrator.Run(new MockGlobalRunSpec(), mnt.Root, @"c:\temp"); } } diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/RegionTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/RegionTests.cs index 5064ab155e4..f5abe736c6b 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/RegionTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/RegionTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/ReplacementTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/ReplacementTests.cs index c55edb641ea..643d0fb04fc 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/ReplacementTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/ReplacementTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/SetFlagTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/SetFlagTests.cs index c8a30cb207e..022f667ee96 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/SetFlagTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/SetFlagTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Operations; @@ -27,7 +26,7 @@ public void TurnOffConditionalTest() string originalValue = @"lead stuff //#if (true) true stuff -//#else +//#else false stuff //#endif Entering Conditional processing = off @@ -36,7 +35,7 @@ false stuff //#if (true) in-conditional true (IF) stuff //#else - in-conditional ELSE stuff + in-conditional ELSE stuff //#endif ...about to exit //+:cnd @@ -56,7 +55,7 @@ true stuff //#if (true) in-conditional true (IF) stuff //#else - in-conditional ELSE stuff + in-conditional ELSE stuff //#endif ...about to exit //+:cnd @@ -85,7 +84,7 @@ public void TurnOffConditionalAndFlagsDontEmitTest() string originalValue = @"lead stuff //#if (true) true stuff -//#else +//#else false stuff //#endif Entering Conditional processing = off @@ -94,7 +93,7 @@ false stuff //#if (true) in-conditional true (IF) stuff //#else - in-conditional ELSE stuff + in-conditional ELSE stuff //#endif ...about to exit //+:cnd:noEmit @@ -113,7 +112,7 @@ true stuff //#if (true) in-conditional true (IF) stuff //#else - in-conditional ELSE stuff + in-conditional ELSE stuff //#endif ...about to exit After Conditional processing = off @@ -171,12 +170,10 @@ public void ValidateConditionOnStartOfFileWithBOM() { string originalValue = @"//-:cnd:noEmit #if DEBUG -using System; #endif //+:cnd:noEmit"; string expectedValue = @"#if DEBUG -using System; #endif "; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/StreamProxyTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/StreamProxyTests.cs index e52ce1214d4..768a6f104b4 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/StreamProxyTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/StreamProxyTests.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; -using System.Linq; using FluentAssertions; using Microsoft.TemplateEngine.Core.Util; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs index 43fe88da607..8cddbe30be6 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/TestBase.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Core.Contracts; using Xunit; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/TokenTrieTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/TokenTrieTests.cs index 422dc7ba82c..ec2f09ac7ce 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/TokenTrieTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/TokenTrieTests.cs @@ -15,7 +15,7 @@ public class TokenTrieTests [InlineData("Hello There!", 1, 1, false, "Hello", " ", null)] [InlineData("Hello There!", 5, 6, true, null, " ", "There!")] [InlineData("Hello There!", 0, 6, true, "Hello", " ", "There!")] - public void VerifyTokenTrieLookArounds(string original, int checkPosition, int expectedPosition, bool success, string after, string value, string before) + public void VerifyTokenTrieLookArounds(string original, int checkPosition, int expectedPosition, bool success, string? after, string value, string? before) { byte[] data = Encoding.UTF8.GetBytes(original); @@ -42,21 +42,21 @@ public void VerifyTokenTrieLookArounds(string original, int checkPosition, int e [Fact(DisplayName = nameof(VerifyTokenTrieAtBegin))] public void VerifyTokenTrieAtBegin() { - byte[] hello = Encoding.UTF8.GetBytes("hello"); - byte[] helloBang = Encoding.UTF8.GetBytes("hello!"); - byte[] hi = Encoding.UTF8.GetBytes("hi"); + byte[] hello = "hello"u8.ToArray(); + byte[] helloBang = "hello!"u8.ToArray(); + byte[] hi = "hi"u8.ToArray(); TokenTrie t = new TokenTrie(); t.AddToken(hello); t.AddToken(helloBang); t.AddToken(hi); - byte[] source1 = Encoding.UTF8.GetBytes("hello there"); - byte[] source2 = Encoding.UTF8.GetBytes("hello1 there"); - byte[] source3 = Encoding.UTF8.GetBytes("hello! there"); - byte[] source4 = Encoding.UTF8.GetBytes("hi there"); - byte[] source5 = Encoding.UTF8.GetBytes("hi"); - byte[] source6 = Encoding.UTF8.GetBytes("he"); + byte[] source1 = "hello there"u8.ToArray(); + byte[] source2 = "hello1 there"u8.ToArray(); + byte[] source3 = "hello! there"u8.ToArray(); + byte[] source4 = "hi there"u8.ToArray(); + byte[] source5 = "hi"u8.ToArray(); + byte[] source6 = "he"u8.ToArray(); int pos = 0; Assert.True(t.GetOperation(source1, source1.Length, ref pos, out int token)); @@ -86,15 +86,15 @@ public void VerifyTokenTrieAtBegin() [Fact(DisplayName = nameof(VerifyTokenTrieNotEnoughBufferLeft))] public void VerifyTokenTrieNotEnoughBufferLeft() { - byte[] hello = Encoding.UTF8.GetBytes("hello"); - byte[] helloBang = Encoding.UTF8.GetBytes("hello!"); + byte[] hello = "hello"u8.ToArray(); + byte[] helloBang = "hello!"u8.ToArray(); TokenTrie t = new TokenTrie(); t.AddToken(hello); t.AddToken(helloBang); - byte[] source1 = Encoding.UTF8.GetBytes("hi"); - byte[] source2 = Encoding.UTF8.GetBytes(" hello"); + byte[] source1 = "hi"u8.ToArray(); + byte[] source2 = " hello"u8.ToArray(); int pos = 0; Assert.False(t.GetOperation(source1, source1.Length, ref pos, out int token)); @@ -112,10 +112,10 @@ public void VerifyTokenTrieNotEnoughBufferLeft() [Fact(DisplayName = nameof(VerifyTokenTrieCombine))] public void VerifyTokenTrieCombine() { - byte[] hello = Encoding.UTF8.GetBytes("hello"); - byte[] helloBang = Encoding.UTF8.GetBytes("hello!"); - byte[] hi = Encoding.UTF8.GetBytes("hi"); - byte[] there = Encoding.UTF8.GetBytes("there!"); + byte[] hello = "hello"u8.ToArray(); + byte[] helloBang = "hello!"u8.ToArray(); + byte[] hi = "hi"u8.ToArray(); + byte[] there = "there!"u8.ToArray(); TokenTrie t = new TokenTrie(); t.AddToken(hello); @@ -129,10 +129,10 @@ public void VerifyTokenTrieCombine() combined.Append(t); combined.Append(t2); - byte[] source1 = Encoding.UTF8.GetBytes("hello there"); - byte[] source2 = Encoding.UTF8.GetBytes("hello! there"); - byte[] source3 = Encoding.UTF8.GetBytes("hi there"); - byte[] source4 = Encoding.UTF8.GetBytes("there!"); + byte[] source1 = "hello there"u8.ToArray(); + byte[] source2 = "hello! there"u8.ToArray(); + byte[] source3 = "hi there"u8.ToArray(); + byte[] source4 = "there!"u8.ToArray(); int pos = 0; Assert.True(t.GetOperation(source1, source1.Length, ref pos, out int token)); diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/TrieTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/TrieTests.cs index 9db2a09d384..20d1b946503 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/TrieTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/TrieTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Util; diff --git a/test/Microsoft.TemplateEngine.Core.UnitTests/VariablesTests.cs b/test/Microsoft.TemplateEngine.Core.UnitTests/VariablesTests.cs index cb2260716ef..000bde3b0b4 100644 --- a/test/Microsoft.TemplateEngine.Core.UnitTests/VariablesTests.cs +++ b/test/Microsoft.TemplateEngine.Core.UnitTests/VariablesTests.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/GeneratorTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/GeneratorTests.cs index 32313d76623..13e8dc73c11 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/GeneratorTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/GeneratorTests.cs @@ -74,7 +74,7 @@ private class CustomGenerator : IGenerator { public Guid Id { get; } = new Guid("{AB083D9D-857A-419E-8394-113F97FFBD6B}"); - public object? ConvertParameterValueToType(IEngineEnvironmentSettings environmentSettings, ITemplateParameter parameter, string untypedValue, out bool valueResolutionError) => throw new NotImplementedException(); + public object ConvertParameterValueToType(IEngineEnvironmentSettings environmentSettings, ITemplateParameter parameter, string untypedValue, out bool valueResolutionError) => throw new NotImplementedException(); [Obsolete] public Task CreateAsync(IEngineEnvironmentSettings environmentSettings, ITemplate template, IParameterSet parameters, string targetDirectory, CancellationToken cancellationToken) => throw new NotImplementedException(); @@ -154,11 +154,11 @@ public Template(IGenerator generator, IMountPoint mountPoint) public bool IsNameAgreementWithFolderPreferred => false; - public string? Author => "Microsoft"; + public string Author => "Microsoft"; - public string? Description => "This is the description"; + public string Description => "This is the description"; - public IReadOnlyList Classifications => Array.Empty(); + public IReadOnlyList Classifications => []; public string? DefaultName => null; @@ -204,15 +204,15 @@ public Template(IGenerator generator, IMountPoint mountPoint) public IReadOnlyList ShortNameList => new[] { ShortName }; - public IReadOnlyList PostActions => Array.Empty(); + public IReadOnlyList PostActions => []; - public IReadOnlyList Constraints => Array.Empty(); + public IReadOnlyList Constraints => []; public IFileSystemInfo? HostSpecificConfiguration => null; public bool IsValid => true; - public IReadOnlyList ValidationErrors => Array.Empty(); + public IReadOnlyList ValidationErrors => []; public IReadOnlyDictionary Localizations { get; } = new Dictionary(); @@ -260,7 +260,7 @@ private SimpleCreationResult() { } public static ICreationResult Instance { get; } = new SimpleCreationResult(); - public IReadOnlyList PostActions { get; } = Array.Empty(); + public IReadOnlyList PostActions { get; } = []; public IReadOnlyList PrimaryOutputs => new[] { CreationPath.Instance }; diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs index f1b31d3efc6..228e09bb56c 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/LocalizationTests.cs @@ -24,7 +24,7 @@ public LocalizationTests(EnvironmentSettingsHelper environmentSettingsHelper) [InlineData(null, "name")] [InlineData("de-DE", "name_de-DE:äÄßöÖüÜ")] [InlineData("tr-TR", "name_tr-TR:çÇğĞıIİöÖşŞüÜ")] - public void TestLocalizedTemplateName(string locale, string expectedName) + public void TestLocalizedTemplateName(string? locale, string expectedName) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); @@ -35,7 +35,7 @@ public void TestLocalizedTemplateName(string locale, string expectedName) [InlineData(null, "desc")] [InlineData("de-DE", "desc_de-DE:äÄßöÖüÜ")] [InlineData("tr-TR", "desc_tr-TR:çÇğĞıIİöÖşŞüÜ")] - public void TestLocalizedTemplateDescription(string locale, string expectedDescription) + public void TestLocalizedTemplateDescription(string? locale, string expectedDescription) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); @@ -46,7 +46,7 @@ public void TestLocalizedTemplateDescription(string locale, string expectedDescr [InlineData(null, "someSymbol", "sym0_displayName")] [InlineData("de-DE", "someSymbol", "sym0_displayName_de-DE:äÄßöÖüÜ")] [InlineData("tr-TR", "someSymbol", "sym0_displayName_tr-TR:çÇğĞıIİöÖşŞüÜ")] - public void TestLocalizedSymbolDisplayName(string locale, string symbolName, string expectedDisplayName) + public void TestLocalizedSymbolDisplayName(string? locale, string symbolName, string expectedDisplayName) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); @@ -59,7 +59,7 @@ public void TestLocalizedSymbolDisplayName(string locale, string symbolName, str [InlineData(null, "someChoice", "sym1_displayName")] [InlineData("de-DE", "someChoice", "sym1_displayName")] [InlineData("tr-TR", "someChoice", "sym1_displayName_tr-TR:çÇğĞıIİöÖşŞüÜ")] - public void TestLocalizedSymbolChoiceDisplayName(string locale, string symbolName, string expectedDisplayName) + public void TestLocalizedSymbolChoiceDisplayName(string? locale, string symbolName, string expectedDisplayName) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); @@ -72,7 +72,7 @@ public void TestLocalizedSymbolChoiceDisplayName(string locale, string symbolNam [InlineData(null, "sym0_desc")] [InlineData("de-DE", "sym0_desc_de-DE:äÄßöÖüÜ")] [InlineData("tr-TR", "sym0_desc_tr-TR:çÇğĞıIİöÖşŞüÜ")] - public void TestLocalizedSymbolDescription(string locale, string expectedDescription) + public void TestLocalizedSymbolDescription(string? locale, string expectedDescription) { _ = LoadHostWithLocalizationTemplates(locale, out _, out ITemplateInfo localizationTemplate); @@ -86,7 +86,7 @@ public void TestLocalizedSymbolDescription(string locale, string expectedDescrip [InlineData("de-DE", "sym1_desc_de-DE:äÄßöÖüÜ", "sym1_choice0_de-DE:äÄßöÖüÜ", "sym1_choice1_de-DE:äÄßöÖüÜ", "sym1_choice2")] [InlineData("tr-TR", "sym1_desc_tr-TR:çÇğĞıIİöÖşŞüÜ", "sym1_choice0_tr-TR:çÇğĞıIİöÖşŞüÜ", "sym1_choice1", "sym1_choice2_tr-TR:çÇğĞıIİöÖşŞüÜ")] public void TestLocalizedSymbolChoices( - string locale, + string? locale, string symbolDesc, string choice0Desc, string choice1Desc, @@ -117,7 +117,7 @@ public void TestLocalizedSymbolChoices( [InlineData(1, "tr-TR", "pa1_desc_tr-TR:çÇğĞıIİöÖşŞüÜ", "pa1_manualInstructions0_tr-TR:çÇğĞıIİöÖşŞüÜ")] public async Task TestLocalizedPostActionFields( int postActionIndex, - string locale, + string? locale, string expectedDescription, string expectedManualInstructions) { @@ -156,7 +156,7 @@ public void TestLocaleCountryFallback(string locale, string expectedName) Assert.Equal(expectedName, localizationTemplate.Name); } - private IEngineEnvironmentSettings LoadHostWithLocalizationTemplates(string locale, out TemplatePackageManager templatePackageManager, out ITemplateInfo localizationTemplate) + private IEngineEnvironmentSettings LoadHostWithLocalizationTemplates(string? locale, out TemplatePackageManager templatePackageManager, out ITemplateInfo localizationTemplate) { var builtins = BuiltInTemplatePackagesProviderFactory.GetComponents(GetTestTemplateLocation("TemplateWithLocalization")); var env = _environmentSettingsHelper.CreateEnvironment(locale: locale, additionalComponents: builtins); diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/Microsoft.TemplateEngine.Edge.UnitTests.csproj b/test/Microsoft.TemplateEngine.Edge.UnitTests/Microsoft.TemplateEngine.Edge.UnitTests.csproj index 3bcab053c26..7b7f81c7576 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/Microsoft.TemplateEngine.Edge.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/Microsoft.TemplateEngine.Edge.UnitTests.csproj @@ -1,8 +1,7 @@ - + + - $(NETCoreTargetFramework);$(NETFullTargetFramework) - $(NETCoreTargetFramework) - enable + $(NetCurrent);$(NetFrameworkCurrent) @@ -18,11 +17,8 @@ + - - - - diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/Mocks/MockPackageManager.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/Mocks/MockPackageManager.cs index 9f83fe4d110..f379d97999d 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/Mocks/MockPackageManager.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/Mocks/MockPackageManager.cs @@ -62,7 +62,7 @@ public Task DownloadPackageAsync(string downloadPath, string i DefaultFeed, identifier, version ?? string.Empty, - Array.Empty())); + [])); } public Task<(string LatestVersion, bool IsLatestVersion, IReadOnlyList Vulnerabilities)> GetLatestVersionAsync(string identifier, string? version = null) diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetInstallerTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetInstallerTests.cs index 8c6e4689243..b64ea187494 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetInstallerTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetInstallerTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Reflection; using FluentAssertions; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; @@ -104,7 +103,7 @@ public async Task CanInstall_CannotInstallFile() MockPackageManager mockPackageManager = new MockPackageManager(); NuGetInstaller installer = new NuGetInstaller(factory, engineEnvironmentSettings, installPath, mockPackageManager, mockPackageManager); - string package = typeof(NuGetInstallerTests).GetTypeInfo().Assembly.Location; + string package = typeof(NuGetInstallerTests).Assembly.Location; InstallRequest request = new InstallRequest(package); Assert.False(await installer.CanInstallAsync(request, CancellationToken.None)); @@ -174,7 +173,7 @@ public async Task Install_LocalPackage_CannotInstallUnsupportedRequest() MockPackageManager mockPackageManager = new MockPackageManager(); NuGetInstaller installer = new NuGetInstaller(factory, engineEnvironmentSettings, installPath, mockPackageManager, mockPackageManager); - string package = typeof(NuGetInstallerTests).GetTypeInfo().Assembly.Location; + string package = typeof(NuGetInstallerTests).Assembly.Location; InstallRequest request = new InstallRequest(package); InstallResult installResult = await installer.InstallAsync(request, provider, CancellationToken.None); diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetVersionHelperTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetVersionHelperTests.cs index 89c04dc8731..96a6ed01dd3 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetVersionHelperTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/NuGetVersionHelperTests.cs @@ -23,7 +23,7 @@ public class NuGetVersionHelperTests [InlineData("*.1", false)] [InlineData("a.b", false)] [InlineData("a.b.*", false)] - public void IsSupportedVersionStringTest(string versionString, bool isSupported) + public void IsSupportedVersionStringTest(string? versionString, bool isSupported) { Assert.Equal(isSupported, NuGetVersionHelper.IsSupportedVersionString(versionString)); } @@ -37,7 +37,7 @@ public void IsSupportedVersionStringTest(string versionString, bool isSupported) [InlineData("55.66.77*", true)] [InlineData("123.456.789.012", false)] [InlineData("1.2", false)] - public void TryParseFloatRangeReturnsExpectedBoolFlag(string versionString, bool isFloatingVersion) + public void TryParseFloatRangeReturnsExpectedBoolFlag(string? versionString, bool isFloatingVersion) { Assert.Equal(isFloatingVersion, NuGetVersionHelper.TryParseFloatRangeEx(versionString, out _)); } @@ -48,7 +48,7 @@ public void TryParseFloatRangeReturnsExpectedBoolFlag(string versionString, bool [InlineData("1.2.3.4", "1.2.*", true)] [InlineData("1.2.3.4", "2.2*", false)] [InlineData("1.2.3.4", "1.2.*-*", true)] - public void TryParseFloatRangeMatchingTest(string versionString, string pattern, bool isMatch) + public void TryParseFloatRangeMatchingTest(string versionString, string? pattern, bool isMatch) { NuGetVersion version = new NuGetVersion(versionString); Assert.True(NuGetVersionHelper.TryParseFloatRangeEx(pattern, out FloatRange floatRange)); diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs index a9ff5989b6d..d4c4fa1af0e 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCacheTests.cs @@ -73,9 +73,9 @@ public void PicksCorrectLocator(string currentCulture, string? expectedLocator) IMountPoint mountPoint = A.Fake(); A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); - ScanResult result = new ScanResult(mountPoint, new[] { template }, locators, Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); + ScanResult result = new ScanResult(mountPoint, new[] { template }, locators, []); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); Assert.Equal(currentCulture, templateCache.Locale); Assert.Equal("testIdentity", templateCache.TemplateInfo.Single().Identity); @@ -101,8 +101,8 @@ public void CanHandlePostActions() IMountPoint mountPoint = A.Fake(); A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); - ScanResult result = new ScanResult(mountPoint, new[] { template }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + ScanResult result = new ScanResult(mountPoint, new[] { template }, [], []); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); WriteObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile, templateCache); var readCache = new TemplateCache(ReadObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile)); @@ -126,8 +126,8 @@ public void CanHandleConstraints() IMountPoint mountPoint = A.Fake(); A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); - ScanResult result = new ScanResult(mountPoint, new[] { template }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + ScanResult result = new ScanResult(mountPoint, new[] { template }, [], []); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); WriteObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile, templateCache); var readCache = new TemplateCache(ReadObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile)); @@ -170,8 +170,8 @@ public void CanHandleParameters() IMountPoint mountPoint = A.Fake(); A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); - ScanResult result = new ScanResult(mountPoint, new[] { template }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + ScanResult result = new ScanResult(mountPoint, new[] { template }, [], []); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); WriteObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile, templateCache); var readCache = new TemplateCache(ReadObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile)); @@ -210,8 +210,8 @@ public void CanHandleDefaultName(bool preferDefaultName, string? defaultName) IMountPoint mountPoint = A.Fake(); A.CallTo(() => mountPoint.MountPointUri).Returns("testMount"); - ScanResult result = new ScanResult(mountPoint, new[] { template }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + ScanResult result = new ScanResult(mountPoint, new[] { template }, [], []); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); WriteObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile, templateCache); var readCache = new TemplateCache(ReadObject(environmentSettings.Host.FileSystem, paths.TemplateCacheFile)); @@ -245,7 +245,7 @@ public void ProducesCorrectWarningOnOverlappingIdentity_ManagedCandidatesOnly() $"{Environment.NewLine} • 'TemplateC' from 'PackageC'" + $"{Environment.NewLine}The template from 'TemplateC' will be used. To resolve this conflict, uninstall the conflicting template packages."; - ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); + ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, [], []); _ = new TemplateCache(new[] { managedTPA, managedTPB, managedTPC }, new[] { result }, new Dictionary(), environmentSettings); var warningMessages = loggedMessages.Where(log => log.Item1 == LogLevel.Warning); @@ -275,7 +275,7 @@ public void ProducesCorrectOutputOnOverlappingIdentity_ManagedAndUnmanagedCandid $"{Environment.NewLine} • 'TemplateC' from 'PackageC'" + $"{Environment.NewLine}The template from 'TemplateC' will be used. To resolve this conflict, uninstall the conflicting template packages."; - ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); + ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, [], []); _ = new TemplateCache(new[] { managedTPA, managedTPB, managedTPC }, new[] { result }, new Dictionary(), environmentSettings); var warningMessages = loggedMessages.Where(log => log.Item1 == LogLevel.Warning); @@ -300,7 +300,7 @@ public void NoOutputOnOverlappingIdentity_UnmanagedCandidateWins() var templateC = GetFakedTemplate(overlappingIdentity, "testMountC", "TemplateC"); var managedTPC = GetFakedTemplatePackage("testMountC"); - ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); + ScanResult result = new ScanResult(A.Fake(), new[] { templateA, templateB, templateC }, [], []); _ = new TemplateCache(new[] { managedTPA, managedTPB, managedTPC }, new[] { result }, new Dictionary(), environmentSettings); var warningMessages = loggedMessages.Where(log => log.Item1 == LogLevel.Warning); @@ -346,8 +346,8 @@ public void CanHandleHostData() using IMountPoint sourceMountPoint = environmentSettings.MountPath(sourceBasePath); A.CallTo(() => template.GeneratorId).Returns(new("0C434DF7-E2CB-4DEE-B216-D7C58C8EB4B3")); // runnable projects generator ID - ScanResult result = new ScanResult(sourceMountPoint, new[] { template }, Array.Empty(), Array.Empty<(string AssemblyPath, Type InterfaceType, IIdentifiedComponent Instance)>()); - TemplateCache templateCache = new TemplateCache(Array.Empty(), new[] { result }, new Dictionary(), environmentSettings); + ScanResult result = new ScanResult(sourceMountPoint, new[] { template }, [], []); + TemplateCache templateCache = new TemplateCache([], new[] { result }, new Dictionary(), environmentSettings); Assert.Equal(hostFileLocation, templateCache.TemplateInfo[0].HostConfigPlace); Assert.Equal(hostFileFormatted, templateCache.TemplateInfo[0].HostData); @@ -392,23 +392,19 @@ private ITemplatePackage GetFakedTemplatePackage(string mountPointUri) private static JObject ReadObject(IPhysicalFileSystem fileSystem, string path) { - using (var fileStream = fileSystem.OpenRead(path)) - using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) - using (var jsonReader = new JsonTextReader(textReader)) - { - return JObject.Load(jsonReader); - } + using var fileStream = fileSystem.OpenRead(path); + using var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true); + using var jsonReader = new JsonTextReader(textReader); + return JObject.Load(jsonReader); } private static void WriteObject(IPhysicalFileSystem fileSystem, string path, object obj) { - using (var fileStream = fileSystem.CreateFile(path)) - using (var textWriter = new StreamWriter(fileStream, System.Text.Encoding.UTF8)) - using (var jsonWriter = new JsonTextWriter(textWriter)) - { - var serializer = new JsonSerializer(); - serializer.Serialize(jsonWriter, obj); - } + using var fileStream = fileSystem.CreateFile(path); + using var textWriter = new StreamWriter(fileStream, System.Text.Encoding.UTF8); + using var jsonWriter = new JsonTextWriter(textWriter); + var serializer = new JsonSerializer(); + serializer.Serialize(jsonWriter, obj); } } } diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCreatorTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCreatorTests.cs index b38357c6cbd..c3ca50c69dc 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCreatorTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplateCreatorTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Castle.Core.Internal; using FluentAssertions; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -101,7 +100,7 @@ public TemplateCreatorTests(EnvironmentSettingsHelper environmentSettingsHelper) [InlineData(true, XmlConditionWithinMsBuildConditionSource, XmlConditionWithinMsBuildConditionOutputOnTrue)] [InlineData(false, MsBuildConditionWithinXmlConditionSource, MsBuildConditionWithinXmlConditionOutputOnFalse)] [InlineData(true, MsBuildConditionWithinXmlConditionSource, MsBuildConditionWithinXmlConditionOutputOnTrue)] - public async void InstantiateAsync_XmlConditionsAndComments(bool paramA, string sourceSnippet, string expectedOutput) + public async Task InstantiateAsync_XmlConditionsAndComments(bool paramA, string sourceSnippet, string expectedOutput) { IReadOnlyDictionary parameters = new Dictionary() { @@ -160,7 +159,7 @@ await InstantiateAsyncHelper( [InlineData(null, "SECOND", false)] // explicit unset [InlineData("", "UNKNOWN", false)] - public async void InstantiateAsync_ParamsProperlyHonored(string? parameterValue, string expectedOutput, bool instantiateShouldFail) + public async Task InstantiateAsync_ParamsProperlyHonored(string? parameterValue, string expectedOutput, bool instantiateShouldFail) { string sourceSnippet = """ #if( ChoiceParam == FirstChoice ) @@ -216,7 +215,7 @@ await InstantiateAsyncHelper( [InlineData(true, false, false, "A,", true)] // Theoretically the result is deterministic, but we'd need to understand the expression tree as well (and purge it) [InlineData(true, false, true, "B,C", true)] - public async void InstantiateAsync_ConditionalParametersCycleEvaluation(bool a_val, bool b_val, bool c_val, string expectedOutput, bool instantiateShouldFail) + public async Task InstantiateAsync_ConditionalParametersCycleEvaluation(bool a_val, bool b_val, bool c_val, string expectedOutput, bool instantiateShouldFail) { // // Template content preparation @@ -290,7 +289,7 @@ await InstantiateAsyncHelper( [InlineData(null, false, null, "", false, null)] [InlineData(false, false, false, "", false, null)] [InlineData(true, false, true, "A,C", false, null)] - public async void InstantiateAsync_ConditionalParametersIsRequiredEvaluation(bool? a_val, bool? b_val, bool? c_val, string expectedOutput, bool instantiateShouldFail, string expectedErrorMessage) + public async Task InstantiateAsync_ConditionalParametersIsRequiredEvaluation(bool? a_val, bool? b_val, bool? c_val, string expectedOutput, bool instantiateShouldFail, string? expectedErrorMessage) { // // Template content preparation @@ -371,14 +370,14 @@ await InstantiateAsyncHelper( [InlineData(true, null, "true", "false", "A,", false, null)] [InlineData(true, null, "true", null, "A,", false, null)] [InlineData(null, true, null, null, "", true, "B")] - public async void InstantiateAsync_ConditionalParametersRequiredOverwrittenByDisabled( + public async Task InstantiateAsync_ConditionalParametersRequiredOverwrittenByDisabled( bool? a_enable_val, bool? b_enable_val, string? a, string? b, string expectedOutput, bool instantiateShouldFail, - string expectedErrorMessage) + string? expectedErrorMessage) { // // Template content preparation @@ -445,12 +444,12 @@ await InstantiateAsyncHelper( [InlineData(true, true, "", false, null)] [InlineData(null, false, "", false, null)] [InlineData(null, true, "A,", false, null)] - public async void InstantiateAsync_ConditionalParametersInversedEnablingCondition( + public async Task InstantiateAsync_ConditionalParametersInversedEnablingCondition( bool? a_disable_val, bool? a, string expectedOutput, bool instantiateShouldFail, - string expectedErrorMessage) + string? expectedErrorMessage) { // // Template content preparation @@ -546,11 +545,11 @@ await InstantiateAsyncHelper( [InlineData(ParamSnippetBooleanDefaultFalse, "A,", false, null)] [InlineData(ParamSnippetBooleanDefaultTrue, "notA,", false, null)] //[InlineData(false, true, "A,", false, null)] - public async void InstantiateAsync_ConditionalParametersEvaluationBehavior( + public async Task InstantiateAsync_ConditionalParametersEvaluationBehavior( string paramSnippet, string expectedOutput, bool instantiateShouldFail, - string expectedErrorMessage) + string? expectedErrorMessage) { // // Template content preparation @@ -627,7 +626,7 @@ await InstantiateAsyncHelper( [InlineData(null, true, false, null, true, null, /*c_val*/ true, "", true, "parB")] [InlineData(null, true, true, null, false, null, /*c_val*/ true, "", true, "parA")] [InlineData(null, true, false, null, false, false, /*c_val*/ false, "", true, @"Attempt to pass result of external evaluation of parameters conditions for parameter(s) that do not have appropriate condition set in template (IsEnabled or IsRequired attributes not populated with condition): B (parameter)")] - public async void InstantiateAsync_ConditionalParametersWithExternalEvaluation( + public async Task InstantiateAsync_ConditionalParametersWithExternalEvaluation( bool? a_val, bool? a_enabled, bool? a_required, @@ -710,7 +709,7 @@ await InstantiateAsyncHelper( [InlineData(TemplateConfigPreferDefaultNameWithDefaultName, null, "./defaultName.cs", false, "")] [InlineData(TemplateConfigNoPreferDefaultNameWithDefaultName, null, "./tst2.cs", false, "")] [InlineData(TemplateConfigPreferDefaultNameWithoutDefaultName, null, "./tst2.cs", true, "Failed to create template: the template name is not specified. Template configuration does not configure a default name that can be used when name is not specified. Specify the name for the template when instantiating or configure a default name in the template configuration.")] - public async void InstantiateAsync_PreferDefaultName(string templateConfig, string? name, string expectedOutputName, bool instanceFailure, string errorMessage) + public async Task InstantiateAsync_PreferDefaultName(string templateConfig, string? name, string expectedOutputName, bool instanceFailure, string errorMessage) { string sourceSnippet = """ using System; @@ -729,7 +728,7 @@ await InstantiateAsyncHelper( } [Fact] - public async void InstantiateAsync_InvalidTemplate() + public async Task InstantiateAsync_InvalidTemplate() { List<(LogLevel Level, string Message)> loggedMessages = new(); InMemoryLoggerProvider loggerProvider = new InMemoryLoggerProvider(loggedMessages); @@ -801,7 +800,7 @@ [Info][MV010] Missing 'classifications'. } [Fact] - public async void InstantiateAsync_InvalidLocalization() + public async Task InstantiateAsync_InvalidLocalization() { List<(LogLevel Level, string Message)> loggedMessages = new(); InMemoryLoggerProvider loggerProvider = new InMemoryLoggerProvider(loggedMessages); @@ -876,7 +875,7 @@ private async Task InstantiateAsyncHelper( string templateSnippet, string sourceSnippet, string expectedOutput, - string expectedErrorMessage, + string? expectedErrorMessage, bool instantiateShouldFail, string? name = "sourceFile", string expectedOutputName = "./sourceFile.cs", @@ -980,7 +979,7 @@ private async Task InstantiateAsyncHelper( res.ErrorMessage.Should().NotBeNullOrEmpty(); res.ErrorMessage.Should().Contain(expectedErrorMessage); res.OutputBaseDirectory.Should().Match(s => - s.IsNullOrEmpty() || !_engineEnvironmentSettings.Host.FileSystem.FileExists(s)); + string.IsNullOrEmpty(s) || !_engineEnvironmentSettings.Host.FileSystem.FileExists(s)); } else { diff --git a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplatePackageManagerTests.cs b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplatePackageManagerTests.cs index 0ef04eb2b01..1b47408e79f 100644 --- a/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplatePackageManagerTests.cs +++ b/test/Microsoft.TemplateEngine.Edge.UnitTests/TemplatePackageManagerTests.cs @@ -164,14 +164,14 @@ public async Task EnsureCacheIsLoadedOnlyOnce() await templatePackageManager2.GetTemplatesAsync(default); Assert.Contains(new SettingsFilePaths(engineEnvironmentSettings).TemplateCacheFile, monitoredFileSystem.FilesOpened); // No mount points should have been scanned - AssertMountPointsWereOpened(Array.Empty(), engineEnvironmentSettings); + AssertMountPointsWereOpened([], engineEnvironmentSettings); // Execute 3rd time with same templatePackageManager to test that TemplateCacheFile is not parsed. monitoredFileSystem.Reset(); await templatePackageManager2.GetTemplatesAsync(default); Assert.DoesNotContain(new SettingsFilePaths(engineEnvironmentSettings).TemplateCacheFile, monitoredFileSystem.FilesOpened); // No mount points should have been scanned - AssertMountPointsWereOpened(Array.Empty(), engineEnvironmentSettings); + AssertMountPointsWereOpened([], engineEnvironmentSettings); } [Fact] @@ -212,7 +212,7 @@ public async Task RebuildCacheIfForceRebuildScansAll() monitoredFileSystem.Reset(); await templatePackageManager.GetTemplatesAsync(default); // Make sure that we don't rescan with force=false - AssertMountPointsWereOpened(Array.Empty(), engineEnvironmentSettings); + AssertMountPointsWereOpened([], engineEnvironmentSettings); monitoredFileSystem.Reset(); await templatePackageManager.RebuildTemplateCacheAsync(default); @@ -222,7 +222,7 @@ public async Task RebuildCacheIfForceRebuildScansAll() monitoredFileSystem.Reset(); await templatePackageManager.GetTemplatesAsync(default); // Make sure that we don't rescan with force=false - AssertMountPointsWereOpened(Array.Empty(), engineEnvironmentSettings); + AssertMountPointsWereOpened([], engineEnvironmentSettings); } [Fact] @@ -249,7 +249,7 @@ public async Task EnsureCacheRoundtripPreservesTemplateWithLocaleTimestamp() monitoredFileSystem.Reset(); await templatePackageManager.GetTemplatesAsync(default); // Make sure that we don't rescan with force=false - AssertMountPointsWereOpened(Array.Empty(), engineEnvironmentSettings); + AssertMountPointsWereOpened([], engineEnvironmentSettings); } [Fact] @@ -351,7 +351,7 @@ public bool TryMount(IEngineEnvironmentSettings environmentSettings, IMountPoint } } - public interface IManagedInstallerMock : IInstaller, ISerializableInstaller { } + public interface IManagedInstallerMock : IInstaller, ISerializableInstaller; internal IManagedInstallerMock GetInstallerMock(IInstallerFactory factory) { @@ -448,17 +448,6 @@ public static void SetNuPkgsAndFolders(IEnumerable? nupkgs = null, IEnum Folders = folders; } - public static void TriggerChanged() - { - foreach (var provider in AllCreatedProviders) - { - if (provider.TryGetTarget(out var actualProvider)) - { - actualProvider.UpdatePackages(NuPkgs, Folders); - } - } - } - public static int StaticPriority { get; set; } public ITemplatePackageProvider CreateProvider(IEngineEnvironmentSettings settings) diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TESTPROJECT3.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TESTPROJECT3.cs index 8acb59def0c..612586fd639 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TESTPROJECT3.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TESTPROJECT3.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TestProject1.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TestProject1.cs index d82f4e13521..121a3e69517 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TestProject1.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/TestProject1.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/testproject2.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/testproject2.cs index 2c3f78a4daf..24525ffbe44 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/testproject2.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/testproject2.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/uc/BAZ.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/uc/BAZ.cs index 9a63a23ca06..cc57727a2c8 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/uc/BAZ.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Approvals/LegacyTests.Renames_FileRenames.verified/TestAssets.TemplateWithRenames/uc/BAZ.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BasicTests.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BasicTests.cs index 0d618539ba1..377d5c86eca 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BasicTests.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BasicTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.TemplateEngine.Abstractions; -using Microsoft.TemplateEngine.Abstractions.TemplateFiltering; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.IDE.IntegrationTests.Utils; using Microsoft.TemplateEngine.TestHelper; @@ -10,7 +9,6 @@ namespace Microsoft.TemplateEngine.IDE.IntegrationTests { - [UsesVerify] [Collection("Verify Tests")] public class BasicTests : BootstrapperTestBase, IClassFixture { @@ -122,7 +120,7 @@ internal async Task Create_TemplateWithBinaryFile_Folder() string output = TestUtils.CreateTemporaryFolder(); var foundTemplates = await bootstrapper.GetTemplatesAsync(new[] { WellKnownSearchFilters.NameFilter("TestAssets.TemplateWithBinaryFile") }); - var result = await bootstrapper.CreateAsync(foundTemplates[0].Info, "my-test-folder", output, new Dictionary()); + await bootstrapper.CreateAsync(foundTemplates[0].Info, "my-test-folder", output, new Dictionary()); string sourceImage = Path.Combine(templateLocation, "image.png"); string targetImage = Path.Combine(output, "image.png"); @@ -147,7 +145,7 @@ internal async Task Create_TemplateWithBinaryFile_Package() string output = TestUtils.CreateTemporaryFolder(); var foundTemplates = await bootstrapper.GetTemplatesAsync(new[] { WellKnownSearchFilters.NameFilter("TestAssets.TemplateWithBinaryFile") }); - var result = await bootstrapper.CreateAsync(foundTemplates[0].Info, "my-test-folder", output, new Dictionary()); + await bootstrapper.CreateAsync(foundTemplates[0].Info, "my-test-folder", output, new Dictionary()); string sourceImage = Path.Combine(templateLocation, "image.png"); string targetImage = Path.Combine(output, "image.png"); @@ -166,7 +164,7 @@ internal async Task GetTemplates_BasicTest() using Bootstrapper bootstrapper = GetBootstrapper(loadTestTemplates: true); var result1 = await bootstrapper.GetTemplatesAsync(default); - var result2 = await bootstrapper.GetTemplatesAsync(Array.Empty>(), cancellationToken: default); + var result2 = await bootstrapper.GetTemplatesAsync([], cancellationToken: default); Assert.NotEmpty(result1); Assert.Equal(result1.Count, result2.Count); diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BootstrapperTestBase.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BootstrapperTestBase.cs index 02fce29c8c5..3eccff099df 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BootstrapperTestBase.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/BootstrapperTestBase.cs @@ -92,7 +92,7 @@ private static ITemplateEngineHost CreateHost(bool loadTestTemplates = false, IE TestLoggerFactory loggerFactory = new(); addLoggerProviders?.ToList().ForEach(loggerFactory.AddProvider); - return new DefaultTemplateEngineHost(HostIdentifier + Guid.NewGuid().ToString(), HostVersion, preferences, builtIns, Array.Empty(), loggerFactory); + return new DefaultTemplateEngineHost(HostIdentifier + Guid.NewGuid().ToString(), HostVersion, preferences, builtIns, [], loggerFactory); } } } diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/ConfigurationTests.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/ConfigurationTests.cs index 5e7d0294ce6..61ce9af47a4 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/ConfigurationTests.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/ConfigurationTests.cs @@ -20,7 +20,7 @@ internal async Task PhysicalConfigurationTest() try { var builtIns = BuiltInTemplatePackagesProviderFactory.GetComponents(TestTemplatesLocation); - var host = new DefaultTemplateEngineHost(nameof(PhysicalConfigurationTest).ToString(), "1.0.0", null, builtIns, Array.Empty()); + var host = new DefaultTemplateEngineHost(nameof(PhysicalConfigurationTest).ToString(), "1.0.0", null, builtIns, []); Bootstrapper bootstrapper = new Bootstrapper(host, virtualizeConfiguration: false, loadDefaultComponents: true); var result = await bootstrapper.GetTemplatesAsync(cancellationToken: default); @@ -46,7 +46,7 @@ internal async Task VirtualConfigurationTest() var hostDir = Path.Combine(baseDir, nameof(VirtualConfigurationTest).ToString()); var builtIns = BuiltInTemplatePackagesProviderFactory.GetComponents(TestTemplatesLocation); - var host = new DefaultTemplateEngineHost(nameof(VirtualConfigurationTest).ToString(), "1.0.0", null, builtIns, Array.Empty()); + var host = new DefaultTemplateEngineHost(nameof(VirtualConfigurationTest).ToString(), "1.0.0", null, builtIns, []); Bootstrapper bootstrapper = new Bootstrapper(host, virtualizeConfiguration: true, loadDefaultComponents: true); var result = await bootstrapper.GetTemplatesAsync(cancellationToken: default); @@ -86,7 +86,7 @@ internal async Task PhysicalConfigurationTest_WithChangedHostLocation() var expectedHostDir = TestUtils.CreateTemporaryFolder(); var builtIns = BuiltInTemplatePackagesProviderFactory.GetComponents(TestTemplatesLocation); - var host = new DefaultTemplateEngineHost(nameof(PhysicalConfigurationTest_WithChangedHostLocation).ToString(), "1.0.0", null, builtIns, Array.Empty()); + var host = new DefaultTemplateEngineHost(nameof(PhysicalConfigurationTest_WithChangedHostLocation).ToString(), "1.0.0", null, builtIns, []); Bootstrapper bootstrapper = new Bootstrapper(host, virtualizeConfiguration: false, loadDefaultComponents: true, hostSettingsLocation: expectedHostDir); var result = await bootstrapper.GetTemplatesAsync(cancellationToken: default); diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/End2EndTests.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/End2EndTests.cs index 160eb2104bc..204228a61a7 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/End2EndTests.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/End2EndTests.cs @@ -10,7 +10,6 @@ namespace Microsoft.TemplateEngine.IDE.IntegrationTests { - [UsesVerify] [Collection("Verify Tests")] public class End2EndTests : BootstrapperTestBase { diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/FileRenameTests.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/FileRenameTests.cs index eef03ee0ccd..4b6999b6cff 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/FileRenameTests.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/FileRenameTests.cs @@ -276,7 +276,7 @@ internal async Task CreateTest(string templateName, string parameters, MockCreat internal async Task GetCreationEffectsTest_Package(string templateName, string parameters, MockCreationEffects expectedResult) { using Bootstrapper bootstrapper = GetBootstrapper(); - string packageLocation = PackTestTemplatesNuGetPackage(_packageManager); + PackTestTemplatesNuGetPackage(_packageManager); await InstallTestTemplateAsync(bootstrapper, templateName); string name = BasicParametersParser.GetNameFromParameterString(parameters); @@ -310,7 +310,7 @@ internal async Task GetCreationEffectsTest_Package(string templateName, string p internal async Task CreateTest_Package(string templateName, string parameters, MockCreationEffects expectedResult) { using Bootstrapper bootstrapper = GetBootstrapper(); - string packageLocation = PackTestTemplatesNuGetPackage(_packageManager); + PackTestTemplatesNuGetPackage(_packageManager); await InstallTestTemplateAsync(bootstrapper, templateName); string name = BasicParametersParser.GetNameFromParameterString(parameters); diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Microsoft.TemplateEngine.IDE.IntegrationTests.csproj b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Microsoft.TemplateEngine.IDE.IntegrationTests.csproj index 873e1048855..d98b24394ef 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Microsoft.TemplateEngine.IDE.IntegrationTests.csproj +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/Microsoft.TemplateEngine.IDE.IntegrationTests.csproj @@ -1,9 +1,9 @@ + - $(NETCoreTargetFramework);$(NETFullTargetFramework) - $(NETCoreTargetFramework) - enable + $(NetCurrent);$(NetFrameworkCurrent) + @@ -18,7 +18,7 @@ - + @@ -32,4 +32,5 @@ + diff --git a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/TemplatePackagesTests.cs b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/TemplatePackagesTests.cs index c3e7893e78d..49e808b6239 100644 --- a/test/Microsoft.TemplateEngine.IDE.IntegrationTests/TemplatePackagesTests.cs +++ b/test/Microsoft.TemplateEngine.IDE.IntegrationTests/TemplatePackagesTests.cs @@ -215,8 +215,7 @@ internal async Task CanUpdateAllPackagesMetadataOnGetLatestVersion() var installedPackages = await bootstrapper.GetManagedTemplatePackagesAsync(CancellationToken.None); // implicitly populates packages metadata - IReadOnlyList checkUpdateResults = await bootstrapper - .GetLatestVersionsAsync(installedPackages, CancellationToken.None); + await bootstrapper.GetLatestVersionsAsync(installedPackages, CancellationToken.None); var updatedPackages = await bootstrapper.GetManagedTemplatePackagesAsync(CancellationToken.None); @@ -242,8 +241,7 @@ internal async Task CanUpdateSpecifiedPackageMetadataOnGetLatestVersion() var boxedTemplatePackage = installedPackages.FirstOrDefault(ip => ip.Identifier == "Boxed.Templates"); // implicitly populates package metadata - IReadOnlyList checkUpdateResults = await bootstrapper - .GetLatestVersionsAsync(new[] { boxedTemplatePackage! }, CancellationToken.None); + await bootstrapper.GetLatestVersionsAsync(new[] { boxedTemplatePackage! }, CancellationToken.None); var updatedPackages = await bootstrapper.GetManagedTemplatePackagesAsync(CancellationToken.None); Assert.Equal(2, updatedPackages.Count); diff --git a/test/Microsoft.TemplateEngine.Mocks/Microsoft.TemplateEngine.Mocks.csproj b/test/Microsoft.TemplateEngine.Mocks/Microsoft.TemplateEngine.Mocks.csproj index f1c54e1df43..19671e2de79 100644 --- a/test/Microsoft.TemplateEngine.Mocks/Microsoft.TemplateEngine.Mocks.csproj +++ b/test/Microsoft.TemplateEngine.Mocks/Microsoft.TemplateEngine.Mocks.csproj @@ -1,11 +1,17 @@ - + + - $(NETStandardTargetFramework);$(NETFullTargetFramework) - $(NETStandardTargetFramework) + $(NetCurrent);$(NetFrameworkCurrent) true - false - false + true + + + + + + annotations + diff --git a/test/Microsoft.TemplateEngine.Mocks/MockCreationEffects.cs b/test/Microsoft.TemplateEngine.Mocks/MockCreationEffects.cs index db1265228da..76870a3ce92 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockCreationEffects.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockCreationEffects.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Xunit.Abstractions; @@ -12,11 +9,11 @@ namespace Microsoft.TemplateEngine.Mocks { public class MockCreationEffects : ICreationEffects, ICreationEffects2, IXunitSerializable { - private string[] _primaryOutputs = Array.Empty(); + private string[] _primaryOutputs = []; - private MockFileChange[] _mockFileChanges = Array.Empty(); + private MockFileChange[] _mockFileChanges = []; - private string[] _absentFiles = Array.Empty(); + private string[] _absentFiles = []; public MockCreationEffects() { diff --git a/test/Microsoft.TemplateEngine.Mocks/MockCreationResult.cs b/test/Microsoft.TemplateEngine.Mocks/MockCreationResult.cs index d943eaf1f79..fad03c5b404 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockCreationResult.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockCreationResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Mocks @@ -11,8 +9,8 @@ public class MockCreationResult : ICreationResult { public MockCreationResult(IReadOnlyList? postActions = null, IReadOnlyList? primaryOutputs = null) { - PostActions = postActions ?? Array.Empty(); - PrimaryOutputs = primaryOutputs ?? Array.Empty(); + PostActions = postActions ?? []; + PrimaryOutputs = primaryOutputs ?? []; } public IReadOnlyList PostActions { get; } diff --git a/test/Microsoft.TemplateEngine.Mocks/MockDirectory.cs b/test/Microsoft.TemplateEngine.Mocks/MockDirectory.cs index 977c7d0a38c..4ea780bc8a8 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockDirectory.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockDirectory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Mocks diff --git a/test/Microsoft.TemplateEngine.Mocks/MockEnvironment.cs b/test/Microsoft.TemplateEngine.Mocks/MockEnvironment.cs index 5c574c3fb01..76e8a3d8fc6 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockEnvironment.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockEnvironment.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Mocks diff --git a/test/Microsoft.TemplateEngine.Mocks/MockFile.cs b/test/Microsoft.TemplateEngine.Mocks/MockFile.cs index 82497dde5e2..0b77824c080 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockFile.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockFile.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions.Mount; namespace Microsoft.TemplateEngine.Mocks diff --git a/test/Microsoft.TemplateEngine.Mocks/MockFileChange.cs b/test/Microsoft.TemplateEngine.Mocks/MockFileChange.cs index 70b780f287d..9fac7362fa1 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockFileChange.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockFileChange.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Xunit.Abstractions; @@ -48,7 +47,7 @@ public string TargetRelativePath public ChangeKind ChangeKind { get; private set; } - public byte[] Contents => Array.Empty(); + public byte[] Contents => []; public void Deserialize(IXunitSerializationInfo info) { diff --git a/test/Microsoft.TemplateEngine.Mocks/MockFileStream.cs b/test/Microsoft.TemplateEngine.Mocks/MockFileStream.cs index 36e68adc4db..9131235714e 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockFileStream.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockFileStream.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; - namespace Microsoft.TemplateEngine.Mocks { public class MockFileStream : MemoryStream diff --git a/test/Microsoft.TemplateEngine.Mocks/MockFileSystem.cs b/test/Microsoft.TemplateEngine.Mocks/MockFileSystem.cs index d981eb29375..0d9c1a358f1 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockFileSystem.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockFileSystem.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; using Microsoft.TemplateEngine.Utils; @@ -68,7 +64,7 @@ public Stream CreateFile(string path) { _files[path] = new FileSystemFile(); } - _files[path].Data = Array.Empty(); + _files[path].Data = []; return new MockFileStream(d => _files[path].Data = d); } @@ -76,7 +72,7 @@ public Stream OpenRead(string path) { if (!_files.TryGetValue(path, out FileSystemFile file)) { - throw new Exception($"File {path} does no texist"); + throw new Exception($"File {path} does not exist"); } MemoryStream s = new MemoryStream(file.Data); @@ -120,7 +116,7 @@ public string ReadAllText(string path) public byte[] ReadAllBytes(string path) { - return _files[path].Data ?? Array.Empty(); + return _files[path].Data ?? []; } public void DirectoryDelete(string path, bool recursive) diff --git a/test/Microsoft.TemplateEngine.Mocks/MockGlobalRunSpec.cs b/test/Microsoft.TemplateEngine.Mocks/MockGlobalRunSpec.cs index e3ea0772e6a..15a6a3fdf2c 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockGlobalRunSpec.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockGlobalRunSpec.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/test/Microsoft.TemplateEngine.Mocks/MockInstallerFactory.cs b/test/Microsoft.TemplateEngine.Mocks/MockInstallerFactory.cs index 667f5d08560..db6b89af0d9 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockInstallerFactory.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockInstallerFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Installer; diff --git a/test/Microsoft.TemplateEngine.Mocks/MockManagedTemplatePackageProvider.cs b/test/Microsoft.TemplateEngine.Mocks/MockManagedTemplatePackageProvider.cs index 2a23cf20a75..bd9920522e8 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockManagedTemplatePackageProvider.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockManagedTemplatePackageProvider.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions.Installer; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; diff --git a/test/Microsoft.TemplateEngine.Mocks/MockMountPoint.cs b/test/Microsoft.TemplateEngine.Mocks/MockMountPoint.cs index f4cdbf27885..f7557586b29 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockMountPoint.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockMountPoint.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.IO; -using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; @@ -33,7 +31,7 @@ public IFileSystemInfo FileSystemInfo(string fullPath) for (int i = 0; i < parts.Length; ++i) { - IFileSystemInfo info = current.EnumerateFileSystemInfos(parts[i], SearchOption.TopDirectoryOnly).FirstOrDefault(); + IFileSystemInfo? info = current.EnumerateFileSystemInfos(parts[i], SearchOption.TopDirectoryOnly).FirstOrDefault(); if (info == null) { diff --git a/test/Microsoft.TemplateEngine.Mocks/MockOperation.cs b/test/Microsoft.TemplateEngine.Mocks/MockOperation.cs index 0f4bb2adb3d..8ef25e9fafe 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockOperation.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockOperation.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; diff --git a/test/Microsoft.TemplateEngine.Mocks/MockPostAction.cs b/test/Microsoft.TemplateEngine.Mocks/MockPostAction.cs index e9af5c538db..5584df48f2b 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockPostAction.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockPostAction.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions; namespace Microsoft.TemplateEngine.Mocks diff --git a/test/Microsoft.TemplateEngine.Mocks/MockTemplateInfo.cs b/test/Microsoft.TemplateEngine.Mocks/MockTemplateInfo.cs index 9acf489294f..c85cd29cbe0 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockTemplateInfo.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockTemplateInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; @@ -21,17 +18,17 @@ public class MockTemplateInfo : ITemplateInfo, IXunitSerializable private Dictionary _parameters = new Dictionary(); - private string[] _baselineInfo = Array.Empty(); + private string[] _baselineInfo = []; - private string[] _classifications = Array.Empty(); + private string[] _classifications = []; - private string[] _shortNameList = Array.Empty(); + private string[] _shortNameList = []; private readonly bool _preferDefaultName = true; - private Guid[] _postActions = Array.Empty(); + private Guid[] _postActions = []; - private TemplateConstraintInfo[] _constraints = Array.Empty(); + private TemplateConstraintInfo[] _constraints = []; private Dictionary _tags = new Dictionary(); diff --git a/test/Microsoft.TemplateEngine.Mocks/MockTemplatePackageInfo.cs b/test/Microsoft.TemplateEngine.Mocks/MockTemplatePackageInfo.cs index db2675206d4..5a0203dcbf2 100644 --- a/test/Microsoft.TemplateEngine.Mocks/MockTemplatePackageInfo.cs +++ b/test/Microsoft.TemplateEngine.Mocks/MockTemplatePackageInfo.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.TemplateSearch.Common.Abstractions; namespace Microsoft.TemplateEngine.Mocks @@ -20,7 +17,7 @@ public MockTemplatePackageInfo(string name, string? version = null, long totalDo Name = name; Version = version; TotalDownloads = totalDownloads; - Owners = owners?.ToArray() ?? Array.Empty(); + Owners = owners?.ToArray() ?? []; } public string Name { get; } diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/BindSymbolTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/BindSymbolTests.cs index ff7a641f5b1..abff40a15ae 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/BindSymbolTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/BindSymbolTests.cs @@ -25,7 +25,7 @@ public BindSymbolTests(EnvironmentSettingsHelper environmentSettingsHelper) } [Fact] - public async void CreateAsyncTest_UseBindValuesWithReplace() + public async Task CreateAsyncTest_UseBindValuesWithReplace() { // // Template content preparation @@ -122,7 +122,7 @@ public async void CreateAsyncTest_UseBindValuesWithReplace() } [Fact] - public async void CreateAsyncTest_UseBindValuesWithFileRename() + public async Task CreateAsyncTest_UseBindValuesWithFileRename() { // // Template content preparation @@ -194,7 +194,7 @@ public async void CreateAsyncTest_UseBindValuesWithFileRename() } [Fact] - public async void CreateAsyncTest_UseBindValuesInMacros() + public async Task CreateAsyncTest_UseBindValuesInMacros() { // // Template content preparation @@ -292,7 +292,7 @@ public async void CreateAsyncTest_UseBindValuesInMacros() } [Fact] - public async void CreateAsyncTest_BindingConflict() + public async Task CreateAsyncTest_BindingConflict() { // // Template content preparation @@ -365,7 +365,7 @@ public async void CreateAsyncTest_BindingConflict() } [Fact] - public async void CreateAsyncTest_ForcedPrefixBinding() + public async Task CreateAsyncTest_ForcedPrefixBinding() { // // Template content preparation @@ -438,7 +438,7 @@ public async void CreateAsyncTest_ForcedPrefixBinding() } [Fact] - public async void CreateAsyncTest_CanUseDefaultValue() + public async Task CreateAsyncTest_CanUseDefaultValue() { // // Template content preparation @@ -530,7 +530,7 @@ public async void CreateAsyncTest_CanUseDefaultValue() } [Fact] - public async void CreateAsyncTest_CanConvertValueToDataType() + public async Task CreateAsyncTest_CanConvertValueToDataType() { // // Template content preparation @@ -609,7 +609,7 @@ public async void CreateAsyncTest_CanConvertValueToDataType() } [Fact] - public async void CreateAsyncTest_NoWarningOnUnknownBindingWithDefaultValue() + public async Task CreateAsyncTest_NoWarningOnUnknownBindingWithDefaultValue() { // // Template content preparation @@ -707,7 +707,7 @@ public TestBindSymbolSource(Guid guid, string prefix = "test", bool requiresPref public int Priority => 0; - public Guid Id { get; private set; } + public Guid Id { get; } public bool RequiresPrefixMatch { get; } diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Constants.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Constants.cs deleted file mode 100644 index 21e47e08b1a..00000000000 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Constants.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests -{ - internal static class Constants - { - internal const string MinimalTemplateConfig = @" -{ - ""identity"": ""test"", - ""name"": ""test"", - ""shortName"": ""test"", -}"; - } -} diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroProcessorTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroProcessorTests.cs index d27d96a8d52..07a4bc6fb5e 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroProcessorTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroProcessorTests.cs @@ -185,11 +185,10 @@ public void CanSortCollectionWithCustomMacroWithDeps() A.CallTo(() => customGeneratedConfig.VariableName).Returns(customMacroName); var customMacroConfig = new FakeMacroConfig(new FakeMacro(), customGeneratedConfig); - var engineEnvironmentSettings = _environmentSettingsHelper.CreateEnvironment( + _environmentSettingsHelper.CreateEnvironment( virtualize: true, environment: A.Fake(), additionalComponents: new[] { (typeof(IMacro), (IIdentifiedComponent)new FakeMacro()) }); - var variableCollection = new VariableCollection(); var sortedItems = MacroProcessor.SortMacroConfigsByDependencies(new[] { customMacroName, switchMacroName, coalesceMacroName }, new[] { (BaseMacroConfig)switchMacroConfig, customMacroConfig, coalesceMacroConfig }); @@ -361,8 +360,6 @@ private class FailMacro : IMacro, IGeneratedSymbolMacro public void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, FailMacroConfig config) => throw new Exception("Failed to evaluate"); - public void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, IGeneratedSymbolConfig generatedSymbolConfig) => throw new Exception("Failed to evaluate"); - public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig config) => throw new Exception("Failed to evaluate"); } @@ -376,8 +373,6 @@ private class FailConfigMacro : IMacro, IGeneratedSymbolMacro public void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, FailMacroConfig config) => throw new Exception("Failed to evaluate"); - public void Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, IGeneratedSymbolConfig generatedSymbolConfig) => throw new TemplateAuthoringException("bad config"); - public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig config) => throw new TemplateAuthoringException("bad config"); } diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/JoinMacroTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/JoinMacroTests.cs index e97caccfa81..3bbe495c30e 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/JoinMacroTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/JoinMacroTests.cs @@ -26,7 +26,7 @@ public JoinMacroTests(EnvironmentSettingsHelper environmentSettingsHelper) [InlineData(",", false)] [InlineData("", false)] [InlineData(null, false)] - public void TestJoinConstantAndReferenceSymbolConfig(string separator, bool removeEmptyValues) + public void TestJoinConstantAndReferenceSymbolConfig(string? separator, bool removeEmptyValues) { string variableName = "joinedParameter"; string referenceSymbolName = "referenceSymbol"; diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/NowMacroTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/NowMacroTests.cs index 091f35e3a29..8b9d4fd2878 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/NowMacroTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/NowMacroTests.cs @@ -77,7 +77,7 @@ public void GeneratedSymbolTest() [InlineData("", "string")] [InlineData("string", "string")] [InlineData("date", "date")] - public void EvaluateNowOverrideDatatypeInConfig(string type, string expectedType) + public void EvaluateNowOverrideDatatypeInConfig(string? type, string expectedType) { string variableName = "nowString"; string format = string.Empty; diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.csproj b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.csproj index 6a9536d6691..68aa13cfed3 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.csproj @@ -1,85 +1,60 @@ - - - $(NETCoreTargetFramework);$(NETFullTargetFramework) - $(NETCoreTargetFramework) - enable - - - - - - - PreserveNewest - - - - - - - - + + + + $(NetCurrent);$(NetFrameworkCurrent) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - Always - - - - - - - - - - - - diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectConfigTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectConfigTests.cs index 4151a07fb65..76a4880bde2 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectConfigTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectConfigTests.cs @@ -154,7 +154,7 @@ public async Task PerformTemplateValidation_ChoiceValuesValidation(string paramD if (expectedToBeValid) { Assert.True(templateConfig.IsValid); - Assert.Empty(templateConfig.ValidationErrors.Where(e => e.Severity is IValidationEntry.SeverityLevel.Error or IValidationEntry.SeverityLevel.Warning)); + Assert.DoesNotContain(templateConfig.ValidationErrors, e => e is { Severity: IValidationEntry.SeverityLevel.Error } or { Severity: IValidationEntry.SeverityLevel.Warning }); } else { diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs index d89c4a2db82..361b26bc723 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs @@ -24,7 +24,7 @@ public RunnableProjectGeneratorTests(EnvironmentSettingsHelper environmentSettin } [Fact] - public async void CreateAsyncTest_GuidsMacroProcessingCaseSensitivity() + public async Task CreateAsyncTest_GuidsMacroProcessingCaseSensitivity() { // // Template content preparation @@ -165,7 +165,7 @@ public async void CreateAsyncTest_GuidsMacroProcessingCaseSensitivity() [Theory] [InlineData(TemplateConfigQuotelessLiteralsNotEnabled, "UNKNOWN")] [InlineData(TemplateConfigQuotelessLiteralsEnabled, "SECOND")] - public async void CreateAsyncTest_ConditionWithUnquotedChoiceLiteral(string templateConfig, string expectedResult) + public async Task CreateAsyncTest_ConditionWithUnquotedChoiceLiteral(string templateConfig, string expectedResult) { // // Template content preparation @@ -224,7 +224,7 @@ public async void CreateAsyncTest_ConditionWithUnquotedChoiceLiteral(string temp } [Fact] - public async void CreateAsyncTest_MultiChoiceParamReplacingAndCondition() + public async Task CreateAsyncTest_MultiChoiceParamReplacingAndCondition() { // // Template content preparation @@ -324,7 +324,7 @@ public async void CreateAsyncTest_MultiChoiceParamReplacingAndCondition() } [Fact] - public async void CreateAsyncTest_MultiChoiceParamAndConditionMacro() + public async Task CreateAsyncTest_MultiChoiceParamAndConditionMacro() { // // Template content preparation @@ -471,7 +471,7 @@ public async void CreateAsyncTest_MultiChoiceParamAndConditionMacro() } [Fact] - public async void CreateAsyncTest_MultiChoiceParamJoining() + public async Task CreateAsyncTest_MultiChoiceParamJoining() { // // Template content preparation @@ -584,7 +584,7 @@ public async void CreateAsyncTest_MultiChoiceParamJoining() } [Fact] - public async void Test_CoaleseWithInvalidSetup() + public async Task Test_CoaleseWithInvalidSetup() { // // Template content preparation @@ -659,7 +659,7 @@ public async void Test_CoaleseWithInvalidSetup() #pragma warning disable xUnit1004 // Test methods should not be skipped [Fact(Skip = "https://github.com/dotnet/templating/issues/4988")] #pragma warning restore xUnit1004 // Test methods should not be skipped - public async void XMLConditionFailure() + public async Task XMLConditionFailure() { // // Template content preparation @@ -745,7 +745,7 @@ This text ensures that buffer is long enough even considering very-very-long env #pragma warning disable xUnit1004 // Test methods should not be skipped [Fact(Skip = "https://github.com/dotnet/templating/issues/4988")] #pragma warning restore xUnit1004 // Test methods should not be skipped - public async void HashConditionFailure() + public async Task HashConditionFailure() { // // Template content preparation diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/JSONSchemaTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/JSONSchemaTests.cs index 6cd8013db50..68886b7105a 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/JSONSchemaTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/JSONSchemaTests.cs @@ -21,22 +21,16 @@ public class JSONSchemaTests : TestBase [InlineData(@"SchemaTests/ConditionalParametersTest.json")] public void IsJSONSchemaValid(string testFile) { - using (TextReader schemaFileStream = File.OpenText(@"SchemaTests/template.json")) - { - JSchema schema = JSchema.Load(new JsonTextReader(schemaFileStream)); - using (TextReader jsonFileStream = File.OpenText(testFile)) - { - using (JsonTextReader jsonReader = new JsonTextReader(jsonFileStream)) - { - JObject templateConfig = (JObject)JToken.ReadFrom(jsonReader); - Assert.True( - templateConfig.IsValid(schema, out IList errors), - "The JSON file is not valid against the schema" + - Environment.NewLine + - string.Join(Environment.NewLine, errors)); - } - } - } + using TextReader schemaFileStream = File.OpenText(@"SchemaTests/template.json"); + JSchema schema = JSchema.Load(new JsonTextReader(schemaFileStream)); + using TextReader jsonFileStream = File.OpenText(testFile); + using JsonTextReader jsonReader = new JsonTextReader(jsonFileStream); + JObject templateConfig = (JObject)JToken.ReadFrom(jsonReader); + Assert.True( + templateConfig.IsValid(schema, out IList errors), + "The JSON file is not valid against the schema" + + Environment.NewLine + + string.Join(Environment.NewLine, errors)); } private static readonly string JsonLocation = Path.Combine(".template.config", "template.json"); diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Serialization/ParameterSymbolJsonConverter.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Serialization/ParameterSymbolJsonConverter.cs index 4a89b3fbd37..b61aa0c7a41 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Serialization/ParameterSymbolJsonConverter.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/Serialization/ParameterSymbolJsonConverter.cs @@ -10,7 +10,7 @@ namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.Seria internal class ParameterSymbolJsonConverter : JsonConverter { //falls back to default de-serializer if not implemented - public override ParameterSymbol? ReadJson(JsonReader reader, Type objectType, ParameterSymbol? existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override ParameterSymbol ReadJson(JsonReader reader, Type objectType, ParameterSymbol? existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); public override void WriteJson(JsonWriter writer, ParameterSymbol? value, JsonSerializer serializer) { diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/FileRenameTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/FileRenameTests.cs index accf956eb6f..dcee0ae64a1 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/FileRenameTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/FileRenameTests.cs @@ -388,7 +388,6 @@ public void CanGenerateFileRenamesForSymbolBasedRenames_Forms() }; using IMountPoint mountPoint = environment.MountPath(sourceBasePath); - object resolvedNameValue = variables["name"]; IReadOnlyDictionary allChanges = FileRenameGenerator.AugmentFileRenames( environment, sourceBasePath, diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/LocalizationTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/LocalizationTests.cs index b734947bc5d..fb7f8c12a9b 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/LocalizationTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/LocalizationTests.cs @@ -112,9 +112,9 @@ public void CanReadDescription(string fileContent, bool errorExpected, string? e public void CanReadNonChoiceSymbol( string fileContent, bool errorExpected, - string expectedSymbolNamesStr, - string expectedSymbolDisplayNamesStr, - string expectedDescriptionsStr) + string? expectedSymbolNamesStr, + string? expectedSymbolDisplayNamesStr, + string? expectedDescriptionsStr) { IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); string tempFolder = environmentSettings.GetTempVirtualizedPath(); @@ -132,15 +132,15 @@ public void CanReadNonChoiceSymbol( Assert.Empty(localizationModel.ParameterSymbols); return; } - string[] expectedSymbolNames = expectedSymbolNamesStr.Split('|'); - string[] expectedDisplayNames = expectedSymbolDisplayNamesStr.Split('|'); - string[] expectedDescriptions = expectedDescriptionsStr.Split('|'); + string[]? expectedSymbolNames = expectedSymbolNamesStr?.Split('|'); + string[]? expectedDisplayNames = expectedSymbolDisplayNamesStr?.Split('|'); + string[]? expectedDescriptions = expectedDescriptionsStr?.Split('|'); - for (int i = 0; i < expectedSymbolNames.Length; i++) + for (int i = 0; i < expectedSymbolNames?.Length; i++) { Assert.True(localizationModel.ParameterSymbols.ContainsKey(expectedSymbolNames[i])); - Assert.Equal(expectedDisplayNames[i] == "(null)" ? null : expectedDisplayNames[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].DisplayName); - Assert.Equal(expectedDescriptions[i] == "(null)" ? null : expectedDescriptions[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].Description); + Assert.Equal(expectedDisplayNames?[i] == "(null)" ? null : expectedDisplayNames?[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].DisplayName); + Assert.Equal(expectedDescriptions?[i] == "(null)" ? null : expectedDescriptions?[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].Description); } } else @@ -173,10 +173,10 @@ public void CanReadNonChoiceSymbol( public void CanReadChoiceSymbol( string fileContent, bool errorExpected, - string expectedSymbolNamesStr, - string expectedSymbolDisplayNamesStr, - string expectedDescriptionsStr, - string expectedChoicesStr) + string? expectedSymbolNamesStr, + string? expectedSymbolDisplayNamesStr, + string? expectedDescriptionsStr, + string? expectedChoicesStr) { IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); string tempFolder = environmentSettings.GetTempVirtualizedPath(); @@ -194,16 +194,16 @@ public void CanReadChoiceSymbol( Assert.Empty(localizationModel.ParameterSymbols); return; } - var expectedSymbolNames = expectedSymbolNamesStr.Split('|'); - var expectedDisplayNames = expectedSymbolDisplayNamesStr.Split('|'); - var expectedDescriptions = expectedDescriptionsStr.Split('|'); + var expectedSymbolNames = expectedSymbolNamesStr?.Split('|'); + var expectedDisplayNames = expectedSymbolDisplayNamesStr?.Split('|'); + var expectedDescriptions = expectedDescriptionsStr?.Split('|'); var expectedChoices = expectedChoicesStr?.Split('|'); - for (int i = 0; i < expectedSymbolNames.Length; i++) + for (int i = 0; i < expectedSymbolNames?.Length; i++) { Assert.True(localizationModel.ParameterSymbols.ContainsKey(expectedSymbolNames[i])); - Assert.Equal(expectedDisplayNames[i] == "(null)" ? null : expectedDisplayNames[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].DisplayName); - Assert.Equal(expectedDescriptions[i] == "(null)" ? null : expectedDescriptions[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].Description); + Assert.Equal(expectedDisplayNames?[i] == "(null)" ? null : expectedDisplayNames?[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].DisplayName); + Assert.Equal(expectedDescriptions?[i] == "(null)" ? null : expectedDescriptions?[i], localizationModel.ParameterSymbols[expectedSymbolNames[i]].Description); if (expectedChoices == null || expectedChoices[i] == "(null)") { @@ -247,9 +247,9 @@ public void CanReadChoiceSymbol( public void CanReadPostAction( string fileContent, bool errorExpected, - string expectedPostActionsStr, - string expectedDescriptionsStr, - string expectedManualInstructionsStr) + string? expectedPostActionsStr, + string? expectedDescriptionsStr, + string? expectedManualInstructionsStr) { IEngineEnvironmentSettings environmentSettings = _environmentSettingsHelper.CreateEnvironment(virtualize: true); string tempFolder = environmentSettings.GetTempVirtualizedPath(); @@ -267,14 +267,14 @@ public void CanReadPostAction( Assert.Empty(localizationModel.PostActions); return; } - var expectedPostActions = expectedPostActionsStr.Split('|'); - var expectedDescriptions = expectedDescriptionsStr.Split('|'); + var expectedPostActions = expectedPostActionsStr?.Split('|'); + var expectedDescriptions = expectedDescriptionsStr?.Split('|'); var expectedInsturctions = expectedManualInstructionsStr?.Split('|'); - for (int i = 0; i < expectedPostActions.Length; i++) + for (int i = 0; i < expectedPostActions?.Length; i++) { Assert.True(localizationModel.PostActions.ContainsKey(expectedPostActions[i])); - Assert.Equal(expectedDescriptions[i] == "(null)" ? null : expectedDescriptions[i], localizationModel.PostActions[expectedPostActions[i]].Description); + Assert.Equal(expectedDescriptions?[i] == "(null)" ? null : expectedDescriptions?[i], localizationModel.PostActions[expectedPostActions[i]].Description); if (expectedInsturctions == null || expectedInsturctions[i] == "(null)") { @@ -387,7 +387,6 @@ public async Task CanValidatePostActionWithDefaultInstructionLocalization() using IMountPoint mountPoint = environmentSettings.MountPath(tempFolder); - string sourceBasePath = environmentSettings.GetTempVirtualizedPath(); IDictionary templateSourceFiles = new Dictionary { // template.json diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/PostActionTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/PostActionTests.cs index a4fd202ced0..b6a821bf5e0 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/PostActionTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/PostActionTests.cs @@ -148,7 +148,7 @@ private static JObject TestTemplateJson [InlineData(true, false, 1, new[] { "Action1", "Default instructions (action 1)" }, null)] [InlineData(false, true, 1, new[] { "Action2", "Default instructions (action 2)" }, null)] [InlineData(false, false, 0, null, null)] - public void TestPostActionConditioning(bool condition1, bool condition2, int expectedActionCount, string[] firstResult, string[] secondResult) + public void TestPostActionConditioning(bool condition1, bool condition2, int expectedActionCount, string[]? firstResult, string[]? secondResult) { TemplateConfigModel configModel = TemplateConfigModel.FromJObject(TestTemplateJson); IVariableCollection vc = new VariableCollection @@ -162,7 +162,7 @@ public void TestPostActionConditioning(bool condition1, bool condition2, int exp "sourceName", "MyProject", vc, - Array.Empty()); + []); List postActions = PostAction.Evaluate( _environmentSettings, @@ -197,7 +197,7 @@ public void TestPostActionConditioning(bool condition1, bool condition2, int exp [InlineData(false, true, 1, "Linux", "Linux instructions (action 2)", null)] [InlineData(false, true, 1, "Mac", "Mac instructions (action 2)", null)] [InlineData(false, true, 1, "BeOS", "Default instructions (action 2)", null)] - public void TestPostActionInstructionsConditioning(bool condition1, bool condition2, int expectedActionCount, string operatingSystemValue, string firstInstruction, string secondInstruction) + public void TestPostActionInstructionsConditioning(bool condition1, bool condition2, int expectedActionCount, string operatingSystemValue, string firstInstruction, string? secondInstruction) { TemplateConfigModel configModel = TemplateConfigModel.FromJObject(TestTemplateJson); IVariableCollection vc = new VariableCollection @@ -212,7 +212,7 @@ public void TestPostActionInstructionsConditioning(bool condition1, bool conditi "sourceName", "MyProject", vc, - Array.Empty()); + []); List postActions = PostAction.Evaluate( _environmentSettings, @@ -247,7 +247,7 @@ public void TestPostActionInstructionsConditioning_BlankCondition() "sourceName", "MyProject", vc, - Array.Empty()); + []); List postActions = PostAction.Evaluate( _environmentSettings, @@ -277,7 +277,7 @@ public void TestPostActionInstructionsConditioning_LastTrueConditionWin() "sourceName", "MyProject", vc, - Array.Empty()); + []); List postActions = PostAction.Evaluate( _environmentSettings, diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SourceConfigTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SourceConfigTests.cs index 0a4b8b1d88c..78f5206feee 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SourceConfigTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SourceConfigTests.cs @@ -64,7 +64,7 @@ public async Task SourceConfigExcludesAreOverriddenByIncludes() using ITemplate template = new RunnableProjectConfig(_engineEnvironmentSettings, generator, templateConfigFile); ParameterSetData parameters = new(template); - ICreationResult result = await (generator as IGenerator).CreateAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); + await (generator as IGenerator).CreateAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); Assert.True(_engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(targetDir, "core.config"))); Assert.False(_engineEnvironmentSettings.Host.FileSystem.FileExists(Path.Combine(targetDir, "full.config"))); } @@ -113,7 +113,6 @@ public async Task CopyOnlyWithoutIncludeDoesntActuallyCopyFile() ParameterSetData parameters = new(template); ICreationEffects result = await (generator as IGenerator).GetCreationEffectsAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); - IEnumerable changes = result.FileChanges.Cast(); Assert.All(result.FileChanges.Cast(), c => c.SourceRelativePath.StartsWith("./")); Assert.Single(result.FileChanges); @@ -164,7 +163,6 @@ public async Task CopyOnlyWithParentIncludeActuallyCopiesFile() ParameterSetData parameters = new(template); ICreationEffects result = await (generator as IGenerator).GetCreationEffectsAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); - IEnumerable changes = result.FileChanges.Cast(); Assert.All(result.FileChanges.Cast(), c => c.SourceRelativePath.StartsWith("./")); Assert.Single(result.FileChanges); @@ -214,7 +212,6 @@ public async Task CopyOnlyWithWildcardAndParentIncludeActuallyCopiesFile() ParameterSetData parameters = new(template); ICreationEffects result = await (generator as IGenerator).GetCreationEffectsAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); - IEnumerable changes = result.FileChanges.Cast(); Assert.All(result.FileChanges.Cast(), c => c.SourceRelativePath.StartsWith("./")); Assert.Single(result.FileChanges); @@ -269,7 +266,6 @@ public async Task IncludeModifierOverridesPreviousExcludeModifierTemplateTest() ParameterSetData parameters = new(template); ICreationEffects result = await (generator as IGenerator).GetCreationEffectsAsync(_engineEnvironmentSettings, template, parameters, targetDir, default); - IEnumerable changes = result.FileChanges.Cast(); Assert.All(result.FileChanges.Cast(), c => c.SourceRelativePath.StartsWith("./")); Assert.Single(result.FileChanges); diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SymbolConfigTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SymbolConfigTests.cs index 3a0a0e6cdc4..eeb88a46bdc 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SymbolConfigTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/SymbolConfigTests.cs @@ -68,59 +68,6 @@ private static JObject ArrayConfigWithNameSymbolAndValueFormsButNotIdentity } } - private static JObject ConfigWithNameSymbolWithoutBinding - { - get - { - string configString = /*lang=json*/ """ - { - "author": "Test Asset", - "classifications": [ "Test Asset" ], - "name": "TemplateWithNameSymbolWithoutBinding", - "generatorVersions": "[1.0.0.0-*)", - "groupIdentity": "TestAssets.TemplateWithNameSymbolWithoutBinding", - "precedence": "100", - "identity": "TestAssets.TemplateWithNameSymbolWithoutBinding", - "shortName": "TestAssets.TemplateWithNameSymbolWithoutBinding", - "symbols": { - "name": { - "type": "parameter", - "dataType": "string", - } - } - } - """; - return JObject.Parse(configString); - } - } - - private static JObject ConfigWithNameSymbolWithCustomBinding - { - get - { - string configString = /*lang=json*/ """ - { - "author": "Test Asset", - "classifications": [ "Test Asset" ], - "name": "ConfigWithNameSymbolWithCustomBinding", - "generatorVersions": "[1.0.0.0-*)", - "groupIdentity": "TestAssets.ConfigWithNameSymbolWithCustomBinding", - "precedence": "100", - "identity": "TestAssets.ConfigWithNameSymbolWithCustomBinding", - "shortName": "TestAssets.ConfigWithNameSymbolWithCustomBinding", - "symbols": { - "name": { - "type": "parameter", - "dataType": "string", - "binding": "customBinding", - } - } - } - """; - return JObject.Parse(configString); - } - } - private static JObject ArrayConfigWithNameSymbolAndValueFormsWithIdentity { get @@ -670,7 +617,7 @@ public void ObjectConfigNameSymbolWithIdentityFormAndAddIdentityFalseRetainsConf ParameterSymbol? nameSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(nameSymbol); - IList configuredValueFormNames = nameSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = nameSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); @@ -688,7 +635,7 @@ public void ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrueRetainsConfi ParameterSymbol? nameSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(nameSymbol); - IList configuredValueFormNames = nameSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = nameSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); @@ -706,7 +653,7 @@ public void NameSymbolObjectValueFormDefinitionRespectsAddIdentityTrue() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueFormFactory.FormIdentifier, configuredValueFormNames[0]); @@ -725,7 +672,7 @@ public void NameSymbolObjectValueFormDefinitionRespectsAddIdentityFalse() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(3, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); @@ -743,7 +690,7 @@ public void NameSymbolObjectValueFormDefinitionInfersAddIdentityTrue() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueFormFactory.FormIdentifier, configuredValueFormNames[0]); @@ -762,7 +709,7 @@ public void NameSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfig ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); @@ -781,7 +728,7 @@ public void ParameterSymbolWithNoValueFormsGetsIdentityFormAdded() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Single(configuredValueFormNames); Assert.Equal(IdentityValueFormFactory.FormIdentifier, configuredValueFormNames[0]); @@ -797,7 +744,7 @@ public void ParameterSymbolWithArrayIdentityValueFormRetainsFormsUnmodified() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); @@ -850,7 +797,7 @@ public void ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityFalseRetain ParameterSymbol? nameSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(nameSymbol); - IList configuredValueFormNames = nameSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = nameSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); @@ -867,7 +814,7 @@ public void ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrueRetains ParameterSymbol? nameSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(nameSymbol); - IList configuredValueFormNames = nameSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = nameSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); @@ -884,7 +831,7 @@ public void ParameterSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsC ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); @@ -902,7 +849,7 @@ public void ParameterSymbolObjectValueFormDefinitionInfersAddIdentityTrue() ParameterSymbol? paramSymbol = symbolInfo as ParameterSymbol; Assert.NotNull(paramSymbol); - IList configuredValueFormNames = paramSymbol!.Forms.GlobalForms.ToList(); + var configuredValueFormNames = paramSymbol!.Forms.GlobalForms; Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueFormFactory.FormIdentifier, configuredValueFormNames[0]); diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateConfigTestHelpers.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateConfigTestHelpers.cs deleted file mode 100644 index 2bfb91a2fa4..00000000000 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateConfigTestHelpers.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Microsoft.TemplateEngine.Core.Contracts; -using Microsoft.TemplateEngine.Mocks; - -namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.TemplateConfigTests -{ - public static class TemplateConfigTestHelpers - { - internal static void SetupFileSourceMatchersOnGlobalRunSpec(MockGlobalRunSpec runSpec, FileSourceMatchInfo source) - { - FileSourceHierarchicalPathMatcher matcher = new FileSourceHierarchicalPathMatcher(source); - runSpec.Include = new List() { new FileSourceStateMatcher(FileDispositionStates.Include, matcher) }; - runSpec.Exclude = new List() { new FileSourceStateMatcher(FileDispositionStates.Exclude, matcher) }; - runSpec.CopyOnly = new List() { new FileSourceStateMatcher(FileDispositionStates.CopyOnly, matcher) }; - runSpec.Rename = source.Renames ?? new Dictionary(StringComparer.Ordinal); - } - } -} diff --git a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateRootTests.cs b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateRootTests.cs index 1a53673d21e..5f6a8f000e9 100644 --- a/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateRootTests.cs +++ b/test/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/TemplateConfigTests/TemplateRootTests.cs @@ -113,7 +113,7 @@ public async Task CheckTemplateRootRelativeToInstallPath(string pathToTemplateJs await templateModel.ValidateAsync(ValidationScope.Instantiation, default); Assert.True(templateModel.IsValid); - Assert.Empty(templateModel.ValidationErrors.Where(e => e.Severity is IValidationEntry.SeverityLevel.Error or IValidationEntry.SeverityLevel.Warning)); + Assert.DoesNotContain(templateModel.ValidationErrors, e => e is { Severity: IValidationEntry.SeverityLevel.Error } or { Severity: IValidationEntry.SeverityLevel.Warning }); } // Tests source paths when the mount point root is the same as the template root. @@ -152,7 +152,7 @@ public async Task CheckTemplateSourcesRelativeToTemplateRoot(bool shouldAllPaths if (shouldAllPathsBeValid) { Assert.True(templateModel.IsValid); - Assert.Empty(templateModel.ValidationErrors.Where(e => e.Severity is IValidationEntry.SeverityLevel.Error or IValidationEntry.SeverityLevel.Warning)); + Assert.DoesNotContain(templateModel.ValidationErrors, e => e is { Severity: IValidationEntry.SeverityLevel.Error } or { Severity: IValidationEntry.SeverityLevel.Warning }); } else { @@ -213,7 +213,7 @@ public async Task CheckTemplateSourcesRelativeToTemplateRootMultipleDirsUnderMou if (shouldAllPathsBeValid) { Assert.True(templateModel.IsValid); - Assert.Empty(templateModel.ValidationErrors.Where(e => e.Severity is IValidationEntry.SeverityLevel.Error or IValidationEntry.SeverityLevel.Warning)); + Assert.DoesNotContain(templateModel.ValidationErrors, e => e is { Severity: IValidationEntry.SeverityLevel.Error } or { Severity: IValidationEntry.SeverityLevel.Warning }); } else { diff --git a/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests.csproj b/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests.csproj index 1cde654f686..b218c68a6be 100644 --- a/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests.csproj @@ -1,12 +1,12 @@ + - $(NETCoreTargetFramework) - false - enable + $(NetCurrent) + diff --git a/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/StringUpdaterTests.cs b/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/StringUpdaterTests.cs index 5106eeb76e3..4651ba51df0 100644 --- a/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/StringUpdaterTests.cs +++ b/test/Microsoft.TemplateEngine.TemplateLocalizer.Core.UnitTests/StringUpdaterTests.cs @@ -45,8 +45,7 @@ public void Dispose() public async Task AllStringsAreWrittenToFile() { CancellationTokenSource cts = new CancellationTokenSource(10000); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); string expectedFilename = Path.Combine(_workingDirectory, "templatestrings.tr.json"); Assert.True(File.Exists(expectedFilename)); @@ -69,8 +68,7 @@ public async Task AllStringsAreWrittenToFile() public async Task DryRunPreventsWritingToFileSystem() { CancellationTokenSource cts = new CancellationTokenSource(10000); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: true, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: true, NullLogger.Instance, cts.Token); string expectedFilename = Path.Combine(_workingDirectory, "templatestrings.tr.json"); Assert.False(File.Exists(expectedFilename)); @@ -80,8 +78,7 @@ public async Task DryRunPreventsWritingToFileSystem() public async Task StringOrderIsPreserved() { CancellationTokenSource cts = new CancellationTokenSource(10000); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); string expectedFilename = Path.Combine(_workingDirectory, "templatestrings.tr.json"); Assert.True(File.Exists(expectedFilename)); @@ -118,8 +115,7 @@ await File.WriteAllTextAsync( }", cts.Token); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "tr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); string fileContent = await File.ReadAllTextAsync(expectedFilename, cts.Token); @@ -141,8 +137,7 @@ await File.WriteAllTextAsync( }", cts.Token); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); string fileContent = await File.ReadAllTextAsync(expectedFilename, cts.Token); @@ -191,8 +186,7 @@ public async Task UnchangedFileShouldntBeOverwritten(bool fileStartsWithBom) // Attempt to update the previously created json to see if it will be overwritten. // The content is identical. So we can read, but we shouldn't write to the file after this point. - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "fr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "fr" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); // An exception will be thrown, failing the test, if the call above tries to write to the file. // The execution should reach this point if the call did not try to write to the file, which indicates success for the test. @@ -213,8 +207,7 @@ await File.WriteAllTextAsync( }", cts.Token); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); string fileContent = await File.ReadAllTextAsync(expectedFilename, cts.Token); @@ -241,8 +234,7 @@ await TemplateStringUpdater.UpdateStringsAsync( _workingDirectory, dryRun: false, NullLogger.Instance, - cts.Token) - ; + cts.Token); string expectedFilename = Path.Combine(_workingDirectory, "templatestrings.it.json"); string fileContent = File.ReadAllText(expectedFilename); @@ -251,8 +243,7 @@ await TemplateStringUpdater.UpdateStringsAsync( Assert.DoesNotContain("\\u00A0", fileContent, StringComparison.OrdinalIgnoreCase); Dictionary resultStrings = - await ReadTemplateStringsFromJsonFile(expectedFilename, cts.Token) - ; + await ReadTemplateStringsFromJsonFile(expectedFilename, cts.Token); Assert.Equal(locStrings.Count, resultStrings.Count); Assert.All(locStrings, x => Assert.Contains(x.Value, resultStrings.Values)); @@ -275,8 +266,7 @@ await File.WriteAllTextAsync( new UTF8Encoding(fileStartsWithBom), cts.Token); - await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token) - ; + await TemplateStringUpdater.UpdateStringsAsync(InputStrings, "en", new string[] { "en" }, _workingDirectory, dryRun: false, NullLogger.Instance, cts.Token); byte[] fileContent = await File.ReadAllBytesAsync(expectedFilename, cts.Token); Assert.Equal(fileStartsWithBom, fileContent.AsSpan().StartsWith(new UTF8Encoding(true).Preamble)); diff --git a/test/Microsoft.TemplateEngine.TestHelper/AssemblyComponentCatalog.cs b/test/Microsoft.TemplateEngine.TestHelper/AssemblyComponentCatalog.cs index e2a0388ac1c..f676466773a 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/AssemblyComponentCatalog.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/AssemblyComponentCatalog.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; using System.Reflection; using Microsoft.TemplateEngine.Abstractions; @@ -44,12 +41,12 @@ public AssemblyComponentCatalog(IReadOnlyList assemblies) { foreach (Type type in asm.GetTypes()) { - if (!typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(type) || type.GetTypeInfo().GetConstructor(Type.EmptyTypes) == null || !type.GetTypeInfo().IsClass || type.IsAbstract) + if (!typeof(IIdentifiedComponent).IsAssignableFrom(type) || type.GetConstructor(Type.EmptyTypes) == null || !type.IsClass || type.IsAbstract) { continue; } - IReadOnlyList registerFor = type.GetTypeInfo().ImplementedInterfaces.Where(x => x != typeof(IIdentifiedComponent) && x != typeof(IPrioritizedComponent) && typeof(IIdentifiedComponent).GetTypeInfo().IsAssignableFrom(x)).ToList(); + IReadOnlyList registerFor = type.GetInterfaces().Where(x => x != typeof(IIdentifiedComponent) && x != typeof(IPrioritizedComponent) && typeof(IIdentifiedComponent).IsAssignableFrom(x)).ToList(); if (registerFor.Count == 0) { continue; @@ -67,7 +64,7 @@ public AssemblyComponentCatalog(IReadOnlyList assemblies) } } - return builder.ToList(); + return builder; } } } diff --git a/test/Microsoft.TemplateEngine.TestHelper/BuiltInTemplatePackagesProvider.cs b/test/Microsoft.TemplateEngine.TestHelper/BuiltInTemplatePackagesProvider.cs index ac8f584cc8e..0934b16b705 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/BuiltInTemplatePackagesProvider.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/BuiltInTemplatePackagesProvider.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.TemplatePackage; diff --git a/test/Microsoft.TemplateEngine.TestHelper/EnvironmentSettingsHelper.cs b/test/Microsoft.TemplateEngine.TestHelper/EnvironmentSettingsHelper.cs index 1edc85e5ef2..2ebc96089a3 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/EnvironmentSettingsHelper.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/EnvironmentSettingsHelper.cs @@ -1,13 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Globalization; -using System.IO; -using System.Linq; using System.Runtime.CompilerServices; -using System.Threading; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge; @@ -83,10 +78,12 @@ public void Dispose() { Directory.Delete(f, true); } - catch + catch (Exception e) when (e is UnauthorizedAccessException or IOException) { - Thread.Sleep(2000); - Directory.Delete(f, true); + // Failed to delete the temporary test folders. + // There may be some access being released prior to this dispose or the machine holding a handle to inner files/folders. + // No need to worry that deletion failed since these folders are in the Temp directory anyway. + // See: https://stackoverflow.com/questions/329355/cannot-delete-directory-with-directory-deletepath-true } } }); diff --git a/test/Microsoft.TemplateEngine.TestHelper/InMemoryLoggerProvider.cs b/test/Microsoft.TemplateEngine.TestHelper/InMemoryLoggerProvider.cs index f456bf59a98..26c1e61fb81 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/InMemoryLoggerProvider.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/InMemoryLoggerProvider.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using Microsoft.Extensions.Logging; namespace Microsoft.TemplateEngine.TestHelper @@ -29,7 +27,7 @@ private class InMemoryLogger : ILogger public InMemoryLogger(List<(LogLevel, string)> messagesCollection) => _messagesCollection = messagesCollection; - public IDisposable? BeginScope(TState state) where TState : notnull + public IDisposable BeginScope(TState state) where TState : notnull { return new Scope(); } diff --git a/test/Microsoft.TemplateEngine.TestHelper/LongRunningConstraintFactory.cs b/test/Microsoft.TemplateEngine.TestHelper/LongRunningConstraintFactory.cs index cc7e19c8ff6..07a309c15d7 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/LongRunningConstraintFactory.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/LongRunningConstraintFactory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; diff --git a/test/Microsoft.TemplateEngine.TestHelper/Microsoft.TemplateEngine.TestHelper.csproj b/test/Microsoft.TemplateEngine.TestHelper/Microsoft.TemplateEngine.TestHelper.csproj index f5283b226e6..075ab499a5f 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/Microsoft.TemplateEngine.TestHelper.csproj +++ b/test/Microsoft.TemplateEngine.TestHelper/Microsoft.TemplateEngine.TestHelper.csproj @@ -1,10 +1,10 @@ - + + + - $(NETFullTargetFramework);$(NETCoreTargetFramework) - $(NETCoreTargetFramework) + $(NetCurrent);$(NetFrameworkCurrent) true false - false true true @@ -17,10 +17,11 @@ - + + \ No newline at end of file diff --git a/test/Microsoft.TemplateEngine.TestHelper/MonitoredFileSystem.cs b/test/Microsoft.TemplateEngine.TestHelper/MonitoredFileSystem.cs index da64b758cf1..c9628a1dc57 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/MonitoredFileSystem.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/MonitoredFileSystem.cs @@ -1,10 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; namespace Microsoft.TemplateEngine.TestHelper diff --git a/test/Microsoft.TemplateEngine.TestHelper/PackageManager.cs b/test/Microsoft.TemplateEngine.TestHelper/PackageManager.cs index 1d659619a62..1a77d0cfd4f 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/PackageManager.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/PackageManager.cs @@ -1,14 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using NuGet.Common; using NuGet.Configuration; using NuGet.Protocol; @@ -173,7 +167,7 @@ internal async Task DownloadPackageAsync( throw new ArgumentException($"{nameof(identifier)} cannot be null or empty", nameof(identifier)); } - IEnumerable packagesSources = LoadNuGetSources(additionalSources?.ToArray() ?? Array.Empty()); + IEnumerable packagesSources = LoadNuGetSources(additionalSources?.ToArray() ?? []); NuGetVersion packageVersion; PackageSource source; @@ -260,8 +254,7 @@ internal async Task DownloadPackageAsync( (PackageSource Source, IEnumerable? FoundPackages)[] foundPackagesBySource = await Task.WhenAll( packageSources.Select(source => - Task.Run(() => GetPackageMetadataAsync(source, packageIdentifier, includePrerelease: true, cancellationToken)))) - ; + Task.Run(() => GetPackageMetadataAsync(source, packageIdentifier, includePrerelease: true, cancellationToken)))); if (!foundPackagesBySource.Where(result => result.FoundPackages != null).Any()) { diff --git a/test/Microsoft.TemplateEngine.TestHelper/TestConstraintFactory.cs b/test/Microsoft.TemplateEngine.TestHelper/TestConstraintFactory.cs index f132b15b591..bedb4bbefa7 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/TestConstraintFactory.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/TestConstraintFactory.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Threading; -using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Constraints; diff --git a/test/Microsoft.TemplateEngine.TestHelper/TestFileSystemUtils.cs b/test/Microsoft.TemplateEngine.TestHelper/TestFileSystemUtils.cs index 15fabcd0f79..106cc5a2904 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/TestFileSystemUtils.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/TestFileSystemUtils.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; diff --git a/test/Microsoft.TemplateEngine.TestHelper/TestHost.cs b/test/Microsoft.TemplateEngine.TestHelper/TestHost.cs index c410864850e..4f0c804b1af 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/TestHost.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/TestHost.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; diff --git a/test/Microsoft.TemplateEngine.TestHelper/TestLoggerFactory.cs b/test/Microsoft.TemplateEngine.TestHelper/TestLoggerFactory.cs index bbb566814d2..9e9db56880e 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/TestLoggerFactory.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/TestLoggerFactory.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.Logging; using Xunit.Abstractions; diff --git a/test/Microsoft.TemplateEngine.TestHelper/TestUtils.cs b/test/Microsoft.TemplateEngine.TestHelper/TestUtils.cs index 6d0862ca227..a08290bdb23 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/TestUtils.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/TestUtils.cs @@ -1,11 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; - namespace Microsoft.TemplateEngine.TestHelper { public static class TestUtils diff --git a/test/Microsoft.TemplateEngine.TestHelper/XunitLoggerProvider.cs b/test/Microsoft.TemplateEngine.TestHelper/XunitLoggerProvider.cs index b7a78be1a14..332fea08b47 100644 --- a/test/Microsoft.TemplateEngine.TestHelper/XunitLoggerProvider.cs +++ b/test/Microsoft.TemplateEngine.TestHelper/XunitLoggerProvider.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Xunit.Abstractions; @@ -119,7 +117,7 @@ public void Log( public bool IsEnabled(LogLevel logLevel) => logLevel >= _minLogLevel; - public IDisposable? BeginScope(TState state) where TState : notnull + public IDisposable BeginScope(TState state) where TState : notnull => new NullScope(); private class NullScope : IDisposable diff --git a/test/Microsoft.TemplateEngine.TestTemplates/Microsoft.TemplateEngine.TestTemplates.csproj b/test/Microsoft.TemplateEngine.TestTemplates/Microsoft.TemplateEngine.TestTemplates.csproj index 7afa3ffa26a..6505f27299d 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/Microsoft.TemplateEngine.TestTemplates.csproj +++ b/test/Microsoft.TemplateEngine.TestTemplates/Microsoft.TemplateEngine.TestTemplates.csproj @@ -1,6 +1,7 @@ + - $(NETCoreTargetFramework) + $(NetCurrent) Template Microsoft.TemplateEngine.TestTemplates Microsoft @@ -10,9 +11,10 @@ content $(NoWarn);NU5128;NU5110;NU5111 true - false + true true + diff --git a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/PostActions/Instructions/Basic/Class1.cs b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/PostActions/Instructions/Basic/Class1.cs index c5c63ecaeb0..a082e956b41 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/PostActions/Instructions/Basic/Class1.cs +++ b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/PostActions/Instructions/Basic/Class1.cs @@ -1,11 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; namespace Microsoft.TemplateEngine.TestTemplates.test_templates.PostActions.RunScript.Basic { diff --git a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MYPROJECT3.cs b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MYPROJECT3.cs index 8acb59def0c..612586fd639 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MYPROJECT3.cs +++ b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MYPROJECT3.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MyProject1.cs b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MyProject1.cs index a1f4b2db1af..baaf3595e39 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MyProject1.cs +++ b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/MyProject1.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/myproject2.cs b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/myproject2.cs index 2c3f78a4daf..24525ffbe44 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/myproject2.cs +++ b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/myproject2.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/uc/bar_uc.cs b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/uc/bar_uc.cs index 084ca300021..b7029210ac0 100644 --- a/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/uc/bar_uc.cs +++ b/test/Microsoft.TemplateEngine.TestTemplates/test_templates/TemplateWithRenames/uc/bar_uc.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Text; namespace Microsoft.TemplateEngine.EndToEndTestHarness.test_templates.TemplateWithRenames diff --git a/test/Microsoft.TemplateEngine.Utils.UnitTests/DirectedGraphTests.cs b/test/Microsoft.TemplateEngine.Utils.UnitTests/DirectedGraphTests.cs index 81f751c97ac..ad88af7039c 100644 --- a/test/Microsoft.TemplateEngine.Utils.UnitTests/DirectedGraphTests.cs +++ b/test/Microsoft.TemplateEngine.Utils.UnitTests/DirectedGraphTests.cs @@ -215,7 +215,7 @@ public void EnumerateTopologicalSortTests(Dictionary> dependen [MemberData(nameof(DirectedGraphSubgraphData))] public void GetSubGraphDependandOnVerticesTests(Dictionary> dependencies, IReadOnlyList vertices, bool includeSeedVertices, Dictionary> expectedResult) { - var result = new DirectedGraph(dependencies).GetSubGraphDependandOnVertices(vertices, includeSeedVertices); + var result = new DirectedGraph(dependencies).GetSubGraphDependentOnVertices(vertices, includeSeedVertices); TestAreEquivalent(result, expectedResult); } @@ -224,9 +224,9 @@ private static void TestAreEquivalent(DirectedGraph actual, Dictionary options.WithoutStrictOrdering()); - foreach (int key in expected.Keys) + foreach (var item in expected) { - actual.DependenciesMap[key].Should().BeEquivalentTo(expected[key], options => options.WithoutStrictOrdering()); + actual.DependenciesMap[item.Key].Should().BeEquivalentTo(item.Value, options => options.WithoutStrictOrdering()); } } } diff --git a/test/Microsoft.TemplateEngine.Utils.UnitTests/Microsoft.TemplateEngine.Utils.UnitTests.csproj b/test/Microsoft.TemplateEngine.Utils.UnitTests/Microsoft.TemplateEngine.Utils.UnitTests.csproj index 928d541b888..01386082a0a 100644 --- a/test/Microsoft.TemplateEngine.Utils.UnitTests/Microsoft.TemplateEngine.Utils.UnitTests.csproj +++ b/test/Microsoft.TemplateEngine.Utils.UnitTests/Microsoft.TemplateEngine.Utils.UnitTests.csproj @@ -1,14 +1,13 @@ - + + - $(NETCoreTargetFramework);$(NETFullTargetFramework) - $(NETCoreTargetFramework) - enable + $(NetCurrent);$(NetFrameworkCurrent) - + diff --git a/test/Microsoft.TemplateEngine.Utils.UnitTests/VersionStringTests.cs b/test/Microsoft.TemplateEngine.Utils.UnitTests/VersionStringTests.cs index 9817b002c9b..deb189ee15e 100644 --- a/test/Microsoft.TemplateEngine.Utils.UnitTests/VersionStringTests.cs +++ b/test/Microsoft.TemplateEngine.Utils.UnitTests/VersionStringTests.cs @@ -21,7 +21,7 @@ public class VersionStringTests [InlineData("A.0.0.0", false)] [InlineData("", false)] [InlineData(null, false)] - public void VerifyVersionIsWellFormedCheckerTest(string versionString, bool expectedParseResult) + public void VerifyVersionIsWellFormedCheckerTest(string? versionString, bool expectedParseResult) { Assert.Equal(expectedParseResult, VersionStringHelpers.IsVersionWellFormed(versionString)); } @@ -36,7 +36,7 @@ public void VerifyVersionIsWellFormedCheckerTest(string versionString, bool expe [InlineData("1.1.0.0", "1.0.0.0", 1)] [InlineData("1.0.0", "1.1", -1)] [InlineData("1.1", "1.0.0", 1)] - public void VerifyVersionComparisonTest(string version1, string version2, int? expectedComparison) + public void VerifyVersionComparisonTest(string? version1, string? version2, int? expectedComparison) { Assert.Equal(expectedComparison, VersionStringHelpers.CompareVersions(version1, version2)); } diff --git a/test/Microsoft.TemplateEngine.Utils.UnitTests/WellKnownSearchFiltersTests.cs b/test/Microsoft.TemplateEngine.Utils.UnitTests/WellKnownSearchFiltersTests.cs index bc702885340..81333ab45a2 100644 --- a/test/Microsoft.TemplateEngine.Utils.UnitTests/WellKnownSearchFiltersTests.cs +++ b/test/Microsoft.TemplateEngine.Utils.UnitTests/WellKnownSearchFiltersTests.cs @@ -14,7 +14,7 @@ public class WellKnownSearchFiltersTests [InlineData("test1||test2", "test1", MatchKind.Exact)] [InlineData("test1||test2", "test", MatchKind.Mismatch)] [InlineData("test1||test2", null, null)] - public void TagFilterTests_TemplateWithTags(string templateTags, string testTag, MatchKind? kind) + public void TagFilterTests_TemplateWithTags(string templateTags, string? testTag, MatchKind? kind) { const string separator = "||"; var templateTagsArray = templateTags.Split(new[] { separator }, System.StringSplitOptions.None); @@ -33,7 +33,7 @@ public void TagFilterTests_TemplateWithTags(string templateTags, string testTag, [Theory] [InlineData("test", MatchKind.Mismatch)] [InlineData(null, null)] - public void TagFilterTests_TemplateWithoutTags(string testTag, MatchKind? kind) + public void TagFilterTests_TemplateWithoutTags(string? testTag, MatchKind? kind) { MockTemplateInfo template = new MockTemplateInfo("console", name: "Long name for Console App", identity: "Console.App.T1", groupIdentity: "Console.App.Test") .WithTag("language", "L1") diff --git a/test/Microsoft.TemplateSearch.Common.UnitTests/Microsoft.TemplateSearch.Common.UnitTests.csproj b/test/Microsoft.TemplateSearch.Common.UnitTests/Microsoft.TemplateSearch.Common.UnitTests.csproj index 25fb8e16553..d7f1c7b705d 100644 --- a/test/Microsoft.TemplateSearch.Common.UnitTests/Microsoft.TemplateSearch.Common.UnitTests.csproj +++ b/test/Microsoft.TemplateSearch.Common.UnitTests/Microsoft.TemplateSearch.Common.UnitTests.csproj @@ -1,7 +1,7 @@ - + + - $(NETCoreTargetFramework) - enable + $(NetCurrent) @@ -15,14 +15,10 @@ - - Always - - - Always - - - Always - + + diff --git a/test/Microsoft.TemplateSearch.Common.UnitTests/MockTemplateSearchSource.cs b/test/Microsoft.TemplateSearch.Common.UnitTests/MockTemplateSearchSource.cs index 1a9911c0118..4e24bca1557 100644 --- a/test/Microsoft.TemplateSearch.Common.UnitTests/MockTemplateSearchSource.cs +++ b/test/Microsoft.TemplateSearch.Common.UnitTests/MockTemplateSearchSource.cs @@ -30,12 +30,11 @@ public ITemplateSearchProvider CreateProvider(IEngineEnvironmentSettings environ public class MockTemplateSearchProvider : ITemplateSearchProvider { - private bool _wasSearched; private ITemplateSearchProviderFactory? _factory; - public bool WasSearched => _wasSearched; + public bool WasSearched { get; private set; } - public IReadOnlyList<(ITemplatePackageInfo PackageInfo, IReadOnlyList MatchedTemplates)> Results { get; set; } = Array.Empty<(ITemplatePackageInfo, IReadOnlyList)>(); + public IReadOnlyList<(ITemplatePackageInfo PackageInfo, IReadOnlyList MatchedTemplates)> Results { get; set; } = []; public ITemplateSearchProviderFactory Factory { @@ -49,7 +48,7 @@ public ITemplateSearchProviderFactory Factory Func> matchingTemplatesFilter, CancellationToken cancellationToken) { - _wasSearched = true; + WasSearched = true; return Task.FromResult(Results); } } diff --git a/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests.csproj b/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests.csproj index 20bae7fee96..3707971ea1a 100644 --- a/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests.csproj +++ b/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests.csproj @@ -1,8 +1,7 @@ - $(NETCoreTargetFramework) - enable + $(NetCurrent) diff --git a/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/NuGetTests.cs b/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/NuGetTests.cs index 4fc0814fd53..c87732d4720 100644 --- a/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/NuGetTests.cs +++ b/test/Microsoft.TemplateSearch.TemplateDiscovery.IntegrationTests/NuGetTests.cs @@ -21,31 +21,29 @@ public async Task CanReadPackageInfo() IReadOnlyList searchResources = indexResource.GetServiceEntries("SearchQueryService"); string queryString = $"{searchResources[0].Uri}?q=Microsoft.DotNet.Common.ProjectTemplates.5.0&skip=0&take=10&prerelease=true&semVerLevel=2.0.0"; Uri queryUri = new Uri(queryString); - using (HttpClient client = new HttpClient()) - using (HttpResponseMessage response = await client.GetAsync(queryUri, CancellationToken.None)) + using HttpClient client = new HttpClient(); + using HttpResponseMessage response = await client.GetAsync(queryUri, CancellationToken.None); + if (response.IsSuccessStatusCode) { - if (response.IsSuccessStatusCode) - { - string responseText = await response.Content.ReadAsStringAsync(CancellationToken.None); + string responseText = await response.Content.ReadAsStringAsync(CancellationToken.None); - NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); - Assert.Equal(1, resultsForPage.TotalHits); - Assert.Single(resultsForPage.Data); + NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); + Assert.Equal(1, resultsForPage.TotalHits); + Assert.Single(resultsForPage.Data); - var packageInfo = resultsForPage.Data[0]; + var packageInfo = resultsForPage.Data[0]; - Assert.Equal("Microsoft.DotNet.Common.ProjectTemplates.5.0", packageInfo.Name); - Assert.NotEmpty(packageInfo.Version); - Assert.True(packageInfo.TotalDownloads > 0); - Assert.True(packageInfo.Reserved); - Assert.Contains("Microsoft", packageInfo.Owners); - packageInfo.Description.Should().NotBeNullOrEmpty(); - packageInfo.IconUrl.Should().NotBeNullOrEmpty(); - } - else - { - Assert.Fail("HTTP request failed."); - } + Assert.Equal("Microsoft.DotNet.Common.ProjectTemplates.5.0", packageInfo.Name); + Assert.NotEmpty(packageInfo.Version); + Assert.True(packageInfo.TotalDownloads > 0); + Assert.True(packageInfo.Reserved); + Assert.Contains("Microsoft", packageInfo.Owners); + packageInfo.Description.Should().NotBeNullOrEmpty(); + packageInfo.IconUrl.Should().NotBeNullOrEmpty(); + } + else + { + Assert.Fail("HTTP request failed."); } } } diff --git a/tools/Directory.Build.props b/tools/Directory.Build.props index f330554d5e6..e4fe79a8347 100644 --- a/tools/Directory.Build.props +++ b/tools/Directory.Build.props @@ -1,8 +1,9 @@ - - + + - true + true + diff --git a/tools/Microsoft.TemplateEngine.Authoring.CLI/Commands/Verify/VerifyCommand.cs b/tools/Microsoft.TemplateEngine.Authoring.CLI/Commands/Verify/VerifyCommand.cs index 4a402e4d4ee..3753c316a9e 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.CLI/Commands/Verify/VerifyCommand.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.CLI/Commands/Verify/VerifyCommand.cs @@ -175,7 +175,7 @@ await engine.Execute( ///
private static void FromAmongCaseInsensitive(CliOption> option, string[]? allowedValues = null, string? allowedHiddenValue = null) { - allowedValues ??= Array.Empty(); + allowedValues ??= []; option.Validators.Add(optionResult => ValidateAllowedValues(optionResult, allowedValues, allowedHiddenValue)); option.CompletionSources.Add(allowedValues); } diff --git a/tools/Microsoft.TemplateEngine.Authoring.CLI/LocalizableStrings.Designer.cs b/tools/Microsoft.TemplateEngine.Authoring.CLI/LocalizableStrings.Designer.cs deleted file mode 100644 index 3336843f6d0..00000000000 --- a/tools/Microsoft.TemplateEngine.Authoring.CLI/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,416 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Authoring.CLI { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Authoring.CLI.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Given a template.config file, creates a "localize" directory next to it and exports the localization files into the created directory. If the localization files already exist, the existing translations will be preserved.. - /// - internal static string command_export_help_description { - get { - return ResourceManager.GetString("command_export_help_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If this option is specified, modified files will not be saved to file system and the changes will only be printed to console output.. - /// - internal static string command_export_help_dryrun_description { - get { - return ResourceManager.GetString("command_export_help_dryrun_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The list of languages to be supported by this template. The following language list will be used as default if this option is omitted: cs, de, en, es, fr, it, ja, ko, pl, pt-BR, ru, tr, zh-Hans, zh-Hant. - /// - internal static string command_export_help_language_description { - get { - return ResourceManager.GetString("command_export_help_language_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to When specified, subdirectories are also searched for template.json files.. - /// - internal static string command_export_help_recursive_description { - get { - return ResourceManager.GetString("command_export_help_recursive_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies the path to the template.json file. If a directory is given, template.json file will be searched within the directory. If --recursive options is specified, all the template.json files under the given directory and its subdirectories will be taken as input.. - /// - internal static string command_export_help_templatePath_description { - get { - return ResourceManager.GetString("command_export_help_templatePath_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to "export" command for the following file was cancelled: "{0}".. - /// - internal static string command_export_log_cancelled { - get { - return ResourceManager.GetString("command_export_log_cancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Execution of "export" command has completed. {0} files were processed.. - /// - internal static string command_export_log_executionEnded { - get { - return ResourceManager.GetString("command_export_log_executionEnded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generating localization files for a template.json has failed. - ///Reason: {0}. - ///File Path: {1}.. - /// - internal static string command_export_log_templateExportFailedWithError { - get { - return ResourceManager.GetString("command_export_log_templateExportFailedWithError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generating localization files for the following template.json file has failed: "{0}".. - /// - internal static string command_export_log_templateExportFailedWithException { - get { - return ResourceManager.GetString("command_export_log_templateExportFailedWithException", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Localization files were successfully generated for the template.json file at path "{0}".. - /// - internal static string command_export_log_templateExportSucceeded { - get { - return ResourceManager.GetString("command_export_log_templateExportSucceeded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to find "template.json" file under the path "{0}".. - /// - internal static string command_export_log_templateJsonNotFound { - get { - return ResourceManager.GetString("command_export_log_templateJsonNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Validates the templates at given location.. - /// - internal static string command_validate_help_description { - get { - return ResourceManager.GetString("command_validate_help_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The location of template(s) to validate.. - /// - internal static string command_validate_help_locationArg_description { - get { - return ResourceManager.GetString("command_validate_help_locationArg_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to <no entries>. - /// - internal static string command_validate_info_no_entries { - get { - return ResourceManager.GetString("command_validate_info_no entries", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Location '{0}': found {1} templates.. - /// - internal static string command_validate_info_scanning_completed { - get { - return ResourceManager.GetString("command_validate_info_scanning_completed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Scanning location '{0}' for the templates... - /// - internal static string command_validate_info_scanning_in_progress { - get { - return ResourceManager.GetString("command_validate_info_scanning_in_progress", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template {0}: the template is not valid.. - /// - internal static string command_validate_info_summary_invalid { - get { - return ResourceManager.GetString("command_validate_info_summary_invalid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' localization for the template {1}: the localization file is not valid. The localization will be skipped.. - /// - internal static string command_validate_info_summary_loc_invalid { - get { - return ResourceManager.GetString("command_validate_info_summary_loc_invalid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to '{0}' localization for the template {1}: the localization file is valid.. - /// - internal static string command_validate_info_summary_loc_valid { - get { - return ResourceManager.GetString("command_validate_info_summary_loc_valid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template {0}: the template is valid.. - /// - internal static string command_validate_info_summary_valid { - get { - return ResourceManager.GetString("command_validate_info_summary_valid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found template {0}:. - /// - internal static string command_validate_info_template_header { - get { - return ResourceManager.GetString("command_validate_info_template_header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Found localization '{0}' for template {1}:. - /// - internal static string command_validate_info_template_loc_header { - get { - return ResourceManager.GetString("command_validate_info_template_loc_header", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Verification Failed.. - /// - internal static string command_verify_error_failed { - get { - return ResourceManager.GetString("command_verify_error_failed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Argument(s) {0} are not recognized. Must be one of: {1}.. - /// - internal static string command_verify_error_unrecognizedArguments { - get { - return ResourceManager.GetString("command_verify_error_unrecognizedArguments", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies pattern(s) defining files to be excluded from verification.. - /// - internal static string command_verify_help_customExcludes_description { - get { - return ResourceManager.GetString("command_verify_help_customExcludes_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies pattern(s) defining files to be included to verification (all files are included if not specified).. - /// - internal static string command_verify_help_customIncludes_description { - get { - return ResourceManager.GetString("command_verify_help_customIncludes_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Runs the template with specified arguments and compares the result with expectations files.. - /// - internal static string command_verify_help_description { - get { - return ResourceManager.GetString("command_verify_help_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If set to true - all template output files will be verified, unless --exclude-pattern option is used.. - /// - internal static string command_verify_help_disableDefaultExcludes_description { - get { - return ResourceManager.GetString("command_verify_help_disableDefaultExcludes_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If set to true - the diff tool won't be automatically started by the Verifier on verification failures.. - /// - internal static string command_verify_help_disableDiffTool_description { - get { - return ResourceManager.GetString("command_verify_help_disableDiffTool_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If set to true - 'dotnet new' command is expected to return non-zero return code.. - /// - internal static string command_verify_help_expectFailure_description { - get { - return ResourceManager.GetString("command_verify_help_expectFailure_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies the path to target directory to output the generated template to.. - /// - internal static string command_verify_help_outputPath_description { - get { - return ResourceManager.GetString("command_verify_help_outputPath_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies optional scenario name to be used in the snapshot folder name.. - /// - internal static string command_verify_help_scenarioName_description { - get { - return ResourceManager.GetString("command_verify_help_scenarioName_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies path to the directory with snapshot files.. - /// - internal static string command_verify_help_snapshotsDirPath_description { - get { - return ResourceManager.GetString("command_verify_help_snapshotsDirPath_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Name of the template to be verified. Can be already installed template or a template within local path specified with -p/--template-path option.. - /// - internal static string command_verify_help_templateName_description { - get { - return ResourceManager.GetString("command_verify_help_templateName_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Specifies the path to the directory with template to be verified.. - /// - internal static string command_verify_help_templatePath_description { - get { - return ResourceManager.GetString("command_verify_help_templatePath_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Sets the Verifier expectations directory naming convention, by indicating which scenarios should be differentiated.. - /// - internal static string command_verify_help_uniqueFor_description { - get { - return ResourceManager.GetString("command_verify_help_uniqueFor_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to If set to true - 'dotnet new' command standard output and error contents will be verified along with the produced template files.. - /// - internal static string command_verify_help_verifyOutputs_description { - get { - return ResourceManager.GetString("command_verify_help_verifyOutputs_description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to "{0}" command has encountered an error. See the logs for more details.. - /// - internal static string generic_log_commandExecutionFailed { - get { - return ResourceManager.GetString("generic_log_commandExecutionFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to There was an error while running the "--{0}" command. Error message: "{1}". See the logs for more details.. - /// - internal static string generic_log_commandExecutionFailedWithErrorMessage { - get { - return ResourceManager.GetString("generic_log_commandExecutionFailedWithErrorMessage", resourceCulture); - } - } - } -} diff --git a/tools/Microsoft.TemplateEngine.Authoring.CLI/Microsoft.TemplateEngine.Authoring.CLI.csproj b/tools/Microsoft.TemplateEngine.Authoring.CLI/Microsoft.TemplateEngine.Authoring.CLI.csproj index 4e955d30af7..c3778a89d8e 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.CLI/Microsoft.TemplateEngine.Authoring.CLI.csproj +++ b/tools/Microsoft.TemplateEngine.Authoring.CLI/Microsoft.TemplateEngine.Authoring.CLI.csproj @@ -2,11 +2,9 @@ Exe - $(NETCoreTargetFramework) + $(NetCurrent) A dotnet CLI tool with commands for template authoring. true - enable - true dotnet-template-authoring @@ -28,22 +26,13 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + + diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/LocalizableStrings.Designer.cs b/tools/Microsoft.TemplateEngine.Authoring.Tasks/LocalizableStrings.Designer.cs deleted file mode 100644 index 93cf4428dcb..00000000000 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Authoring.Tasks { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Authoring.Tasks.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Failed to export localization files for 'template.json' file under the path '{0}': {1}.. - /// - internal static string Localize_Log_ExportTaskFailed { - get { - return ResourceManager.GetString("Localize_Log_ExportTaskFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'LocalizeTemplates' stopped processing the following file, because the operation was cancelled: {0}. - /// - internal static string Localize_Log_FileProcessingCancelled { - get { - return ResourceManager.GetString("Localize_Log_FileProcessingCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to find 'template.json' file under the path '{0}'.. - /// - internal static string Localize_Log_TemplateJsonNotFound { - get { - return ResourceManager.GetString("Localize_Log_TemplateJsonNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The property '{0}' should be set for '{1}' target.. - /// - internal static string Log_Error_MissingRequiredProperty { - get { - return ResourceManager.GetString("Log_Error_MissingRequiredProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Location '{0}': found {1} templates.. - /// - internal static string Validate_Log_FoundTemplate { - get { - return ResourceManager.GetString("Validate_Log_FoundTemplate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template configuration. - /// - internal static string Validate_Log_TemplateConfiguration_Subcategory { - get { - return ResourceManager.GetString("Validate_Log_TemplateConfiguration_Subcategory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template localization. - /// - internal static string Validate_Log_TemplateLocalization_Subcategory { - get { - return ResourceManager.GetString("Validate_Log_TemplateLocalization_Subcategory", resourceCulture); - } - } - } -} diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Microsoft.TemplateEngine.Authoring.Tasks.csproj b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Microsoft.TemplateEngine.Authoring.Tasks.csproj index 6c0f513098d..0f36476820d 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Microsoft.TemplateEngine.Authoring.Tasks.csproj +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Microsoft.TemplateEngine.Authoring.Tasks.csproj @@ -1,57 +1,48 @@ - $(NETStandardTargetFramework) + $(NetToolCurrent);$(NetFrameworkToolCurrent) MSBuild tasks for template authoring. + true + true - tasks - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - true + false + true + tools + $(TargetsForTfmSpecificContentInPackage);AddBuildOutputToPackageNet;AddBuildOutputToPackageNetFramework + + true - - - - - - - - + + - - + + + - - True - True - LocalizableStrings.resx - + - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + - - - + + + + - + - + + diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/LocalizeTemplates.cs b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/LocalizeTemplates.cs index 47debf71afe..0f552a91da0 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/LocalizeTemplates.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/LocalizeTemplates.cs @@ -1,12 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Authoring.Tasks.Utilities; diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/ValidateTemplates.cs b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/ValidateTemplates.cs index de226f22f19..89a67e014df 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/ValidateTemplates.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Tasks/ValidateTemplates.cs @@ -1,13 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Build.Framework; using Microsoft.Extensions.Logging; using Microsoft.TemplateEngine.Abstractions; @@ -88,9 +81,6 @@ private void LogResults(ScanResult scanResult) Log.LogMessage(LocalizableStrings.Validate_Log_FoundTemplate, scanResult.MountPoint.MountPointUri, scanResult.Templates.Count); foreach (IScanTemplateInfo template in scanResult.Templates) { - string templateDisplayName = GetTemplateDisplayName(template); - StringBuilder sb = new(); - LogValidationEntries(LocalizableStrings.Validate_Log_TemplateConfiguration_Subcategory, template.ValidationErrors); foreach (KeyValuePair locator in template.Localizations) { @@ -99,12 +89,6 @@ private void LogResults(ScanResult scanResult) } } - static string GetTemplateDisplayName(IScanTemplateInfo template) - { - string templateName = string.IsNullOrEmpty(template.Name) ? "" : template.Name; - return $"'{templateName}' ({template.Identity})"; - } - void LogValidationEntries(string subCategory, IReadOnlyList errors) { foreach (IValidationEntry error in errors.OrderByDescending(e => e.Severity)) diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Utilities/MSBuildLogger.cs b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Utilities/MSBuildLogger.cs index 5d602601f58..ec7473fa57b 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/Utilities/MSBuildLogger.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/Utilities/MSBuildLogger.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using Microsoft.Build.Utilities; using Microsoft.Extensions.Logging; @@ -23,7 +22,7 @@ public MSBuildLogger(string category, TaskLoggingHelper loggingHelperToWrap) _loggingHelper = loggingHelperToWrap; } - public IDisposable? BeginScope(TState state) where TState : notnull + public IDisposable BeginScope(TState state) where TState : notnull => Scope; public bool IsEnabled(LogLevel logLevel) => true; diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.props b/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.props index ae0b51223bd..4058c0537ab 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.props +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.props @@ -1,6 +1,7 @@ - - + + + true - + diff --git a/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.targets b/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.targets index d1c5ee4974e..78f4c9382ad 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.targets +++ b/tools/Microsoft.TemplateEngine.Authoring.Tasks/build/Microsoft.TemplateEngine.Authoring.Tasks.targets @@ -1,19 +1,28 @@ - + + + - $(MSBuildThisFileDirectory)..\tasks\netstandard2.0\Microsoft.TemplateEngine.Authoring.Tasks.dll + $(MSBuildThisFileDirectory)..\tools\net\Microsoft.TemplateEngine.Authoring.Tasks.dll + $(MSBuildThisFileDirectory)..\tools\netframework\Microsoft.TemplateEngine.Authoring.Tasks.dll - - - + + - - + + diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/LocalizableStrings.Designer.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/LocalizableStrings.Designer.cs deleted file mode 100644 index e698d990009..00000000000 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Authoring.TemplateApiVerifier { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Authoring.TemplateApiVerifier.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to The template "{0}" was created successfully.. - /// - internal static string CreateSuccessful { - get { - return ResourceManager.GetString("CreateSuccessful", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template config: {0} doesn't exist. When using 'WithInstantiationThroughTemplateCreatorApi' the 'TemplatePath' parameter must specify path to the template.json or to the root of template (containing {1}).. - /// - internal static string Error_ConfigDoesntExist { - get { - return ResourceManager.GetString("Error_ConfigDoesntExist", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template configuration file could not be retrieved from configured mount point.. - /// - internal static string Error_ConfigRetrieval { - get { - return ResourceManager.GetString("Error_ConfigRetrieval", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'DotnetExecutablePath' parameter must not be specified when using 'WithInstantiationThroughTemplateCreatorApi'.. - /// - internal static string Error_DotnetPath { - get { - return ResourceManager.GetString("Error_DotnetPath", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to install template: {0}, details: {1}.. - /// - internal static string Error_InstallFail { - get { - return ResourceManager.GetString("Error_InstallFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No packages fetched after installation.. - /// - internal static string Error_NoPackages { - get { - return ResourceManager.GetString("Error_NoPackages", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 'TemplateSpecificArgs' parameter must not be specified when using WithInstantiationThroughTemplateCreatorApi. Parameters should be passed via the argument of 'WithInstantiationThroughTemplateCreatorApi'.. - /// - internal static string Error_TemplateArgsDisalowed { - get { - return ResourceManager.GetString("Error_TemplateArgsDisalowed", resourceCulture); - } - } - } -} diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier.csproj b/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier.csproj index 8df93c143f6..e496990fa04 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier.csproj +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier.csproj @@ -1,11 +1,8 @@ - Library - $(NETCoreTargetFramework) + $(NetCurrent) The extension of templates verification engine enabling verification testing through dotnet template engine API. - false - enable true true @@ -23,17 +20,8 @@ - - True - True - LocalizableStrings.resx - + - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - - diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/TemplateVerifierOptionsExtensions.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/TemplateVerifierOptionsExtensions.cs index d6b6527d038..097acd20a6d 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/TemplateVerifierOptionsExtensions.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateApiVerifier/TemplateVerifierOptionsExtensions.cs @@ -81,7 +81,7 @@ private static async Task RunInstantiation( "1.0.0", null, new List<(Type, IIdentifiedComponent)>(), - Array.Empty()); + []); var bootstrapper = new Bootstrapper( host, diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/IPhysicalFileSystemEx.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/IPhysicalFileSystemEx.cs index abb48993ceb..b0dc7b88e3b 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/IPhysicalFileSystemEx.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/IPhysicalFileSystemEx.cs @@ -8,7 +8,7 @@ namespace Microsoft.TemplateEngine.Authoring.TemplateVerifier internal interface IPhysicalFileSystemEx : IPhysicalFileSystem { /// - /// Same behavior as . + /// Same behavior as . /// Task ReadAllTextAsync(string path, CancellationToken cancellationToken = default); diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/LocalizableStrings.Designer.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/LocalizableStrings.Designer.cs deleted file mode 100644 index 06fe6f9322e..00000000000 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,144 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.Authoring.TemplateVerifier { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.Authoring.TemplateVerifier.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Template installation expected to pass but it had exit code '{0}'.. - /// - internal static string VerificationEngine_Error_InstallUnexpectedFail { - get { - return ResourceManager.GetString("VerificationEngine_Error_InstallUnexpectedFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to File extension passed to scrubber should not start with dot.. - /// - internal static string VerificationEngine_Error_ScrubberExtension { - get { - return ResourceManager.GetString("VerificationEngine_Error_ScrubberExtension", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The folder [{0}] should not exist in the template output - cannot verify stdout/stderr in such case.. - /// - internal static string VerificationEngine_Error_StdOutFolderExists { - get { - return ResourceManager.GetString("VerificationEngine_Error_StdOutFolderExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template name is mandatory, but was not supplied.. - /// - internal static string VerificationEngine_Error_TemplateNameMandatory { - get { - return ResourceManager.GetString("VerificationEngine_Error_TemplateNameMandatory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unexpected error encountered.. - /// - internal static string VerificationEngine_Error_Unexpected { - get { - return ResourceManager.GetString("VerificationEngine_Error_Unexpected", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template instantiation expected to pass but it had exit code '{0}'.. - /// - internal static string VerificationEngine_Error_UnexpectedFail { - get { - return ResourceManager.GetString("VerificationEngine_Error_UnexpectedFail", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template instantiation expected to fail but it passed.. - /// - internal static string VerificationEngine_Error_UnexpectedPass { - get { - return ResourceManager.GetString("VerificationEngine_Error_UnexpectedPass", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Template instantiation expected not to have any stderr output, but stderr output was encountered:{0}{1}. - /// - internal static string VerificationEngine_Error_UnexpectedStdErr { - get { - return ResourceManager.GetString("VerificationEngine_Error_UnexpectedStdErr", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The working directory already exists and is not empty.. - /// - internal static string VerificationEngine_Error_WorkDirExists { - get { - return ResourceManager.GetString("VerificationEngine_Error_WorkDirExists", resourceCulture); - } - } - } -} diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Microsoft.TemplateEngine.Authoring.TemplateVerifier.csproj b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Microsoft.TemplateEngine.Authoring.TemplateVerifier.csproj index 684204b0725..deffd39aa0d 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Microsoft.TemplateEngine.Authoring.TemplateVerifier.csproj +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/Microsoft.TemplateEngine.Authoring.TemplateVerifier.csproj @@ -1,11 +1,9 @@ - Library - $(NETCoreTargetFramework) + $(NetCurrent) The verification engine for the templates for .NET template engine. true - enable true true @@ -27,18 +25,8 @@ - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + @@ -47,4 +35,5 @@ + diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/ScrubbersDefinition.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/ScrubbersDefinition.cs index 31d13bad877..b21ad9cdeef 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/ScrubbersDefinition.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/ScrubbersDefinition.cs @@ -18,11 +18,11 @@ private ScrubbersDefinition() { } public delegate void ScrubFileByPath(string relativeFilePath, StringBuilder content); - internal Dictionary> ScrubersByExtension { get; private set; } = new Dictionary>(); + internal Dictionary> ScrubbersByExtension { get; } = new Dictionary>(); internal Action? GeneralScrubber { get; private set; } - internal List ByPathScrubbers { get; private set; } = new List(); + internal List ByPathScrubbers { get; } = new List(); public ScrubbersDefinition AddScrubber(Action scrubber, string? extension = null) { @@ -44,12 +44,12 @@ public ScrubbersDefinition AddScrubber(Action scrubber, string? e throw new TemplateVerificationException(LocalizableStrings.VerificationEngine_Error_ScrubberExtension, TemplateVerificationErrorCode.InvalidOption); } - if (ScrubersByExtension.TryGetValue(extension, out var origScrubber)) + if (ScrubbersByExtension.TryGetValue(extension, out var origScrubber)) { scrubber = origScrubber + scrubber; } - ScrubersByExtension[extension] = scrubber; + ScrubbersByExtension[extension] = scrubber; } return this; diff --git a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs index e39bad3b01c..64d18d262c6 100644 --- a/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs +++ b/tools/Microsoft.TemplateEngine.Authoring.TemplateVerifier/VerificationEngine.cs @@ -165,7 +165,7 @@ internal static Task CreateVerificationTask( verifySettings.AddScrubber(options.CustomScrubbers.GeneralScrubber); } - foreach (var pair in options.CustomScrubbers.ScrubersByExtension) + foreach (var pair in options.CustomScrubbers.ScrubbersByExtension) { verifySettings.AddScrubber(pair.Key, pair.Value); } @@ -405,7 +405,7 @@ private static void DummyMethod() scrubbers.ByPathScrubbers.ForEach(scrubberByPath => scrubberByPath(relativePath, sb)); } - if (!string.IsNullOrEmpty(extension) && scrubbers.ScrubersByExtension.TryGetValue(extension, out Action? scrubber)) + if (!string.IsNullOrEmpty(extension) && scrubbers.ScrubbersByExtension.TryGetValue(extension, out Action? scrubber)) { sb ??= new StringBuilder(content); scrubber(sb); @@ -429,7 +429,8 @@ private static void DummyMethod() private async Task VerifyResult(TemplateVerifierOptions args, IInstantiationResult commandResultData, CallerInfo callerInfo) { - UsesVerifyAttribute a = new UsesVerifyAttribute(); + UseVerifyAttribute a = new UseVerifyAttribute(); + // https://github.com/VerifyTests/Verify/blob/d8cbe38f527d6788ecadd6205c82803bec3cdfa6/src/Verify.Xunit/Verifier.cs#L10 // need to simulate execution from tests var v = DummyMethod; diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/JsonMemberMissingException.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/JsonMemberMissingException.cs index 895956931b3..5f6dfc52f0c 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/JsonMemberMissingException.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/JsonMemberMissingException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.TemplateLocalizer.Core.Exceptions { /// diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/TemplateLocalizerException.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/TemplateLocalizerException.cs index 5f7dfdc0626..310f8dda300 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/TemplateLocalizerException.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Exceptions/TemplateLocalizerException.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.TemplateLocalizer.Core.Exceptions { /// diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportOptions.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportOptions.cs index 08912a7f185..303ad67d461 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportOptions.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportOptions.cs @@ -1,10 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.Linq; - namespace Microsoft.TemplateEngine.TemplateLocalizer.Core { public readonly struct ExportOptions : IEquatable diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportResult.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportResult.cs index b56067dd158..c2b161d714f 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportResult.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExportResult.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.TemplateLocalizer.Core { /// diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExtendedJavascriptEncoder.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExtendedJavascriptEncoder.cs index 457f9f69f92..5cefa5b3648 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExtendedJavascriptEncoder.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/ExtendedJavascriptEncoder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Buffers; using System.Text; using System.Text.Encodings.Web; diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/LocalizableStrings.Designer.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/LocalizableStrings.Designer.cs deleted file mode 100644 index 25b1dac64a1..00000000000 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/LocalizableStrings.Designer.cs +++ /dev/null @@ -1,153 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.TemplateEngine.TemplateLocalizer.Core { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class LocalizableStrings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal LocalizableStrings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.TemplateEngine.TemplateLocalizer.Core.LocalizableStrings", typeof(LocalizableStrings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Adding into localizable strings: {0}. - /// - internal static string stringExtractor_log_jsonElementAdded { - get { - return ResourceManager.GetString("stringExtractor_log_jsonElementAdded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The following element in the template.json will not be included in the localizations because it does not match any of the rules for localizable elements: {0}. - /// - internal static string stringExtractor_log_jsonElementExcluded { - get { - return ResourceManager.GetString("stringExtractor_log_jsonElementExcluded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Each child of '{0}' should have a unique id. Currently, the id '{1}' is shared by multiple children.. - /// - internal static string stringExtractor_log_jsonKeyIsNotUnique { - get { - return ResourceManager.GetString("stringExtractor_log_jsonKeyIsNotUnique", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Json element '{0}' must have a member '{1}'.. - /// - internal static string stringExtractor_log_jsonMemberIsMissing { - get { - return ResourceManager.GetString("stringExtractor_log_jsonMemberIsMissing", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The following element in the template.json will be skipped since it was already added to the list of localizable strings: {0}. - /// - internal static string stringExtractor_log_skippingAlreadyAddedElement { - get { - return ResourceManager.GetString("stringExtractor_log_skippingAlreadyAddedElement", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The contents of the following file seems to be the same as before. The file will not be overwritten. File: '{0}'. - /// - internal static string stringUpdater_log_dataIsUnchanged { - get { - return ResourceManager.GetString("stringUpdater_log_dataIsUnchanged", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Failed to read the existing strings from '{0}'. - /// - internal static string stringUpdater_log_failedToReadLocFile { - get { - return ResourceManager.GetString("stringUpdater_log_failedToReadLocFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Loading existing localizations from file '{0}'. - /// - internal static string stringUpdater_log_loadingLocFile { - get { - return ResourceManager.GetString("stringUpdater_log_loadingLocFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The file already contains a localized string for key '{0}'. The old value will be preserved.. - /// - internal static string stringUpdater_log_localizedStringAlreadyExists { - get { - return ResourceManager.GetString("stringUpdater_log_localizedStringAlreadyExists", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Opening the following templatestrings.json file for writing: '{0}'. - /// - internal static string stringUpdater_log_openingTemplatesJson { - get { - return ResourceManager.GetString("stringUpdater_log_openingTemplatesJson", resourceCulture); - } - } - } -} diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Microsoft.TemplateEngine.TemplateLocalizer.Core.csproj b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Microsoft.TemplateEngine.TemplateLocalizer.Core.csproj index b88e2b0c968..f2038dda6a4 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Microsoft.TemplateEngine.TemplateLocalizer.Core.csproj +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Microsoft.TemplateEngine.TemplateLocalizer.Core.csproj @@ -1,7 +1,7 @@ - $(NETStandardTargetFramework) + $(NetCurrent);netstandard2.0;$(NetFrameworkCurrent) The core API for Template Localizer tool. true true @@ -9,27 +9,24 @@ true + + + + annotations + + - - True - True - LocalizableStrings.resx - - - - - - ResXFileCodeGenerator - LocalizableStrings.Designer.cs - + + diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateLocalizer.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateLocalizer.cs index a6e96a8ab3d..e5e900676fb 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateLocalizer.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateLocalizer.cs @@ -1,13 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.TemplateEngine.TemplateLocalizer.Core.Exceptions; diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateString.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateString.cs index c4a48b77970..268246d21af 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateString.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateString.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - namespace Microsoft.TemplateEngine.TemplateLocalizer.Core { /// diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringExtractor.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringExtractor.cs index ce7ccc94ea9..063c32ce236 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringExtractor.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringExtractor.cs @@ -3,9 +3,6 @@ #pragma warning disable SA1114 // Comments on parameters be allowed https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2917 -using System; -using System.Collections.Generic; -using System.Linq; using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -25,7 +22,6 @@ internal sealed class TemplateStringExtractor private static readonly IJsonKeyCreator DefaultArrayKeyExtractor = new IndexBasedKeyCreator(); private static readonly IJsonKeyCreator DefaultObjectKeyExtractor = new NameKeyCreator(); - private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; private readonly JsonDocument _jsonDocument; @@ -73,8 +69,8 @@ internal sealed class TemplateStringExtractor public TemplateStringExtractor(JsonDocument document, ILoggerFactory? loggerFactory = null) { _jsonDocument = document; - _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; - _logger = _loggerFactory.CreateLogger(); + ILoggerFactory loggerFactory1 = loggerFactory ?? NullLoggerFactory.Instance; + _logger = loggerFactory1.CreateLogger(); } /// diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringUpdater.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringUpdater.cs index 7a66c9b8f63..2edcb8d3f58 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringUpdater.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TemplateStringUpdater.cs @@ -1,14 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Microsoft.TemplateEngine.TemplateLocalizer.Core @@ -177,7 +171,11 @@ private static async Task TruncateFileWhilePreservingBom(FileStream fileStream, // Read bytes from the stream until we fill the preamble array or hit EOF. do { +#if NET + read = await fileStream.ReadAsync(preamble.AsMemory(offset, preamble.Length - offset), cancellationToken).ConfigureAwait(false); +#else read = await fileStream.ReadAsync(preamble, offset, preamble.Length - offset, cancellationToken).ConfigureAwait(false); +#endif offset += read; // Optimization to not call .ReadAsync twice if (offset == preamble.Length) diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalArgs.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalArgs.cs index c14ca10b916..d8394686c42 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalArgs.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalArgs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.TemplateLocalizer.Core.TraversalRules; namespace Microsoft.TemplateEngine.TemplateLocalizer.Core diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalRules/TraversalRule.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalRules/TraversalRule.cs index 740d58205b7..536b3f7e7ca 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalRules/TraversalRule.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/TraversalRules/TraversalRule.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; using Microsoft.TemplateEngine.TemplateLocalizer.Core.KeyCreators; namespace Microsoft.TemplateEngine.TemplateLocalizer.Core.TraversalRules diff --git a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Utilities/Rune.cs b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Utilities/Rune.cs index 229925b943d..3dd480d4e0b 100644 --- a/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Utilities/Rune.cs +++ b/tools/Microsoft.TemplateEngine.TemplateLocalizer.Core/Utilities/Rune.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#if !NET + using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -542,3 +544,5 @@ public bool TryEncodeToUtf8(Span destination, out int bytesWritten) internal static Rune UnsafeCreate(uint scalarValue) => new(scalarValue, false); } } + +#endif \ No newline at end of file diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostDataProducer.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostDataProducer.cs index c6359163e83..87b549ad91b 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostDataProducer.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostDataProducer.cs @@ -25,7 +25,7 @@ internal CliHostDataProducer() public string DataUniqueName => CliHostDataName; - public object? Data => _hostDataForPackByTemplate; + public object Data => _hostDataForPackByTemplate; public object? CreateDataForTemplate(IScanTemplateInfo template, IEngineEnvironmentSettings environment) { diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateData.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateData.cs index b31c577244e..b86573d9149 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateData.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateData.cs @@ -60,11 +60,11 @@ internal CliHostTemplateData( bool isHidden = false) { SymbolInfo = symbolInfo; - UsageExamples = usageExamples?.ToArray() ?? Array.Empty(); + UsageExamples = usageExamples?.ToArray() ?? []; IsHidden = isHidden; } - public IReadOnlyList UsageExamples { get; } = Array.Empty(); + public IReadOnlyList UsageExamples { get; } = []; public IReadOnlyDictionary> SymbolInfo { get; } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateDataLoader.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateDataLoader.cs index 7a0f09b1dc5..a1fb3452c16 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateDataLoader.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/AdditionalData/CliHostTemplateDataLoader.cs @@ -50,13 +50,10 @@ internal CliHostTemplateData ReadHostSpecificTemplateData(ITemplateInfo template file = mountPoint.FileInfo(templateInfo.HostConfigPlace); if (file != null && file.Exists) { - JObject jsonData; - using (Stream stream = file.OpenRead()) - using (TextReader textReader = new StreamReader(stream, true)) - using (JsonReader jsonReader = new JsonTextReader(textReader)) - { - jsonData = JObject.Load(jsonReader); - } + using Stream stream = file.OpenRead(); + using TextReader textReader = new StreamReader(stream, true); + using JsonReader jsonReader = new JsonTextReader(textReader); + var jsonData = JObject.Load(jsonReader); return new CliHostTemplateData(jsonData); } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Filters/FilterNonMicrosoftAuthors.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Filters/FilterNonMicrosoftAuthors.cs index 155577e8d93..95f687bfe4d 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Filters/FilterNonMicrosoftAuthors.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Filters/FilterNonMicrosoftAuthors.cs @@ -34,15 +34,13 @@ static PreFilterResult Filter(IDownloadedPackInfo packInfo) { try { - using (var streamReader = new StreamReader(templateJson.OpenRead())) - using (var jsonReader = new JsonTextReader(streamReader)) + using var streamReader = new StreamReader(templateJson.OpenRead()); + using var jsonReader = new JsonTextReader(streamReader); + var jObject = JObject.Load(jsonReader); + var author = jObject["author"]?.Value(); + if (author?.Contains("microsoft", StringComparison.OrdinalIgnoreCase) ?? false) { - var jObject = JObject.Load(jsonReader); - var author = jObject["author"]?.Value(); - if (author?.Contains("microsoft", StringComparison.OrdinalIgnoreCase) ?? false) - { - return new PreFilterResult(FilterId, isFiltered: true, $"{templateJson.FullPath} has Author=Microsoft and package id is {packInfo.Name}"); - } + return new PreFilterResult(FilterId, isFiltered: true, $"{templateJson.FullPath} has Author=Microsoft and package id is {packInfo.Name}"); } } catch (Exception) diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Microsoft.TemplateSearch.TemplateDiscovery.csproj b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Microsoft.TemplateSearch.TemplateDiscovery.csproj index e8271e2e623..62967b93a9a 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Microsoft.TemplateSearch.TemplateDiscovery.csproj +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Microsoft.TemplateSearch.TemplateDiscovery.csproj @@ -2,24 +2,25 @@ Exe - $(NETCoreTargetFramework) + $(NetCurrent) true false true - enable - true - - - + + - - + + + + + + @@ -33,4 +34,5 @@ + diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NuGetPackSourceCheckerFactory.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NuGetPackSourceCheckerFactory.cs index 392f53f0495..90d4c27571d 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NuGetPackSourceCheckerFactory.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NuGetPackSourceCheckerFactory.cs @@ -71,12 +71,10 @@ public async Task CreatePackSourceCheckerAsync(CommandArgs co } Verbose.WriteLine($"Opening {fileLocation.FullName}"); - using (var fileStream = fileLocation.OpenRead()) - using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) - using (var jsonReader = new JsonTextReader(textReader)) - { - return new JsonSerializer().Deserialize>(jsonReader); - } + using var fileStream = fileLocation.OpenRead(); + using var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true); + using var jsonReader = new JsonTextReader(textReader); + return new JsonSerializer().Deserialize>(jsonReader); } private static async Task LoadExistingCacheAsync(CommandArgs config, CancellationToken cancellationToken) @@ -92,12 +90,10 @@ public async Task CreatePackSourceCheckerAsync(CommandArgs co cacheFileLocation = new FileInfo("currentSearchCache.json"); } Verbose.WriteLine($"Opening {cacheFileLocation.FullName}"); - using (var fileStream = cacheFileLocation.OpenRead()) - using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) - using (var jsonReader = new JsonTextReader(textReader)) - { - return TemplateSearchCache.FromJObject(JObject.Load(jsonReader), NullLogger.Instance, new Dictionary>() { { CliHostSearchCacheData.DataName, CliHostSearchCacheData.Reader } }); - } + using var fileStream = cacheFileLocation.OpenRead(); + using var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true); + using var jsonReader = new JsonTextReader(textReader); + return TemplateSearchCache.FromJObject(JObject.Load(jsonReader), NullLogger.Instance, new Dictionary>() { { CliHostSearchCacheData.DataName, CliHostSearchCacheData.Reader } }); } private static async Task DownloadUriToFileAsync(string uri, string filePath, CancellationToken cancellationToken) @@ -109,17 +105,13 @@ private static async Task DownloadUriToFileAsync(string uri, string filePath, Ca CheckCertificateRevocationList = true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; - using (HttpClient client = new HttpClient(handler)) - { - using (HttpResponseMessage response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false)) - { - response.EnsureSuccessStatusCode(); - string resultText = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - File.WriteAllText(filePath, resultText); - Verbose.WriteLine($"{uri} was successfully downloaded to {filePath}."); - return; - } - } + using HttpClient client = new HttpClient(handler); + using HttpResponseMessage response = await client.GetAsync(uri, cancellationToken).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + string resultText = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + File.WriteAllText(filePath, resultText); + Verbose.WriteLine($"{uri} was successfully downloaded to {filePath}."); + return; } catch (TaskCanceledException) { diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackProvider.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackProvider.cs index 164eba81d9c..51237a8ca04 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackProvider.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackProvider.cs @@ -45,17 +45,13 @@ internal NuGetPackProvider(string name, string query, DirectoryInfo packageTempB _searchUriFormat = $"{searchResources[0].Uri}?{query}&skip={{0}}&take={{1}}&prerelease={includePreviewPacks}&semVerLevel=2.0.0"; - if (Directory.Exists(_packageTempPath)) - { - throw new Exception($"temp storage path for NuGet packages already exists: {_packageTempPath}"); - } - else + if (!Directory.Exists(_packageTempPath)) { Directory.CreateDirectory(_packageTempPath); } } - public string Name { get; private set; } + public string Name { get; } public bool SupportsGetPackageInfoViaApi => true; @@ -92,45 +88,43 @@ public async IAsyncEnumerable GetCandidatePacksAsync([Enum string queryString = string.Format(_searchUriFormat, skip, pageSize); Uri queryUri = new Uri(queryString); - using (HttpClient client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true })) - using (HttpResponseMessage response = await client.GetAsync(queryUri, token).ConfigureAwait(false)) + using HttpClient client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }); + using HttpResponseMessage response = await client.GetAsync(queryUri, token).ConfigureAwait(false); + if (response.IsSuccessStatusCode) { - if (response.IsSuccessStatusCode) - { - string responseText = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false); + string responseText = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false); - NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); - totalPackCount = resultsForPage.TotalHits; - if (resultsForPage.Data.Count > 0) - { - skip += pageSize; - packCount += resultsForPage.Data.Count; - foreach (NuGetPackageSourceInfo sourceInfo in resultsForPage.Data) - { - yield return sourceInfo; - } - } - //4000 is NuGet limit, stop after 4000 is processed. - if (totalPackCount == packCount || (totalPackCount > 4000 && packCount == 4000)) + NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); + totalPackCount = resultsForPage.TotalHits; + if (resultsForPage.Data.Count > 0) + { + skip += pageSize; + packCount += resultsForPage.Data.Count; + foreach (NuGetPackageSourceInfo sourceInfo in resultsForPage.Data) { - if (totalPackCount > 4000) - { - Console.WriteLine($"Warning: {totalPackCount} packages were found, but only first 4000 packages can be retrieved. Other packages will be skipped."); - } - done = true; + yield return sourceInfo; } - else if (skip > 3000 || skip >= totalPackCount) + } + //4000 is NuGet limit, stop after 4000 is processed. + if (totalPackCount == packCount || (totalPackCount > 4000 && packCount == 4000)) + { + if (totalPackCount > 4000) { - Console.WriteLine($"Failed to get all search results from NuGet: expected {totalPackCount}, retrieved: {packCount}."); - throw new Exception("Failed to get search results from NuGet search API."); + Console.WriteLine($"Warning: {totalPackCount} packages were found, but only first 4000 packages can be retrieved. Other packages will be skipped."); } - + done = true; } - else + else if (skip > 3000 || skip >= totalPackCount) { - Console.WriteLine($"Unexpected response from NuGet: code {response.StatusCode}, details: {response}."); + Console.WriteLine($"Failed to get all search results from NuGet: expected {totalPackCount}, retrieved: {packCount}."); throw new Exception("Failed to get search results from NuGet search API."); } + + } + else + { + Console.WriteLine($"Unexpected response from NuGet: code {response.StatusCode}, details: {response}."); + throw new Exception("Failed to get search results from NuGet search API."); } } while (!done && !_runOnlyOnePage); @@ -143,20 +137,27 @@ public async Task DownloadPackageAsync(ITemplatePackageInfo try { - using Stream packageStream = File.Create(outputPackageFileNameFullPath); - if (await _downloadResource.CopyNupkgToStreamAsync( - packinfo.Name, - new NuGetVersion(packinfo.Version!), - packageStream, - _cacheContext, - NullLogger.Instance, - token).ConfigureAwait(false)) + if (File.Exists(outputPackageFileNameFullPath)) { return new DownloadedPackInfo(packinfo, outputPackageFileNameFullPath); } else { - throw new Exception($"Download failed: {nameof(_downloadResource.CopyNupkgToStreamAsync)} returned false."); + using Stream packageStream = File.Create(outputPackageFileNameFullPath); + if (await _downloadResource.CopyNupkgToStreamAsync( + packinfo.Name, + new NuGetVersion(packinfo.Version!), + packageStream, + _cacheContext, + NullLogger.Instance, + token).ConfigureAwait(false)) + { + return new DownloadedPackInfo(packinfo, outputPackageFileNameFullPath); + } + else + { + throw new Exception($"Download failed: {nameof(_downloadResource.CopyNupkgToStreamAsync)} returned false."); + } } } catch (TaskCanceledException) @@ -174,14 +175,12 @@ public async Task GetPackageCountAsync(CancellationToken token) { string queryString = string.Format(_searchUriFormat, 0, _pageSize); Uri queryUri = new Uri(queryString); - using (HttpClient client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true })) - using (HttpResponseMessage response = await client.GetAsync(queryUri, token).ConfigureAwait(false)) - { - response.EnsureSuccessStatusCode(); - string responseText = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false); - NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); - return resultsForPage.TotalHits; - } + using HttpClient client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }); + using HttpResponseMessage response = await client.GetAsync(queryUri, token).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + string responseText = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false); + NuGetPackageSearchResult resultsForPage = NuGetPackageSearchResult.FromJObject(JObject.Parse(responseText)); + return resultsForPage.TotalHits; } public async Task DeleteDownloadedPacksAsync() @@ -275,7 +274,7 @@ internal NuGetPackInfo(IPackageSearchMetadata packageSearchMetadata) public long TotalDownloads { get; } - public IReadOnlyList Owners => Array.Empty(); + public IReadOnlyList Owners => []; public bool Reserved { get; } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSearchResult.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSearchResult.cs index 79a781a0a02..95b84eb2825 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSearchResult.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSearchResult.cs @@ -10,7 +10,7 @@ internal class NuGetPackageSearchResult { internal int TotalHits { get; private set; } - internal List Data { get; private set; } = new List(); + internal List Data { get; } = new List(); //property names are explained here: https://docs.microsoft.com/en-us/nuget/api/search-query-service-resource internal static NuGetPackageSearchResult FromJObject(JObject entry) diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSourceInfo.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSourceInfo.cs index aeed84d1847..48c3ca03f44 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSourceInfo.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/NuGet/NugetPackageSourceInfo.cs @@ -25,13 +25,13 @@ internal NuGetPackageSourceInfo(string id, string version) Version = version; } - public string Name { get; private set; } + public string Name { get; } - public string Version { get; private set; } + public string Version { get; } public long TotalDownloads { get; private set; } - public IReadOnlyList Owners { get; private set; } = Array.Empty(); + public IReadOnlyList Owners { get; private set; } = []; public bool Reserved { get; private set; } @@ -47,7 +47,7 @@ internal static NuGetPackageSourceInfo FromJObject(JObject entry) NuGetPackageSourceInfo sourceInfo = new NuGetPackageSourceInfo(id, version) { TotalDownloads = entry.ToInt32("totalDownloads"), - Owners = entry.Get("owners").JTokenStringOrArrayToCollection(Array.Empty()), + Owners = entry.Get("owners").JTokenStringOrArrayToCollection([]), Reserved = entry.ToBool("verified"), Description = entry.ToString("description"), IconUrl = entry.ToString("iconUrl") diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/DownloadedPackInfo.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/DownloadedPackInfo.cs index 6e058442d20..dbadba2797b 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/DownloadedPackInfo.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/DownloadedPackInfo.cs @@ -24,7 +24,7 @@ internal DownloadedPackInfo(ITemplatePackageInfo info, string filePath) public string? Version => _info.Version; - public string Path { get; private set; } + public string Path { get; } public long TotalDownloads => _info.TotalDownloads; diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/FilteredPackageInfo.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/FilteredPackageInfo.cs index 8ff6d6969b4..5ea3a2ceaf7 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/FilteredPackageInfo.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/FilteredPackageInfo.cs @@ -6,6 +6,7 @@ namespace Microsoft.TemplateSearch.TemplateDiscovery.PackChecking { + [System.Diagnostics.DebuggerDisplay("{Name}@{Version} - {Reason}")] internal class FilteredPackageInfo : ITemplatePackageInfo { internal FilteredPackageInfo(ITemplatePackageInfo info, string reason) @@ -40,16 +41,16 @@ private FilteredPackageInfo(string name, string reason) public long TotalDownloads { get; private set; } [JsonProperty] - public IReadOnlyList Owners { get; private set; } = Array.Empty(); + public IReadOnlyList Owners { get; private set; } = []; [JsonProperty] public bool Reserved { get; private set; } [JsonIgnore] - public string? Description { get; private set; } + public string? Description { get; } [JsonIgnore] - public string? IconUrl { get; private set; } + public string? IconUrl { get; } } } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/PackSourceChecker.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/PackSourceChecker.cs index 7b26d87b9f1..aa628eceb97 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/PackSourceChecker.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/PackChecking/PackSourceChecker.cs @@ -156,10 +156,10 @@ private async Task CheckRemovedPackagesAsync( var packageInfo = await provider.GetPackageInfoAsync(package.Name, cancellationToken).ConfigureAwait(false); if (packageInfo == default) { - Console.WriteLine($"Package {package.Name} cannot be verified."); - throw new Exception($"Package {package.Name} is missing and cannot be verified."); + Console.WriteLine($"Package {package.Name} no longer exists in the provider."); + scanningStats.RemovedTemplatePacks.Add(package); } - if (packageInfo.Removed) + else if (packageInfo.Removed) { Console.WriteLine($"Package {package.Name} was unlisted."); scanningStats.RemovedTemplatePacks.Add(package); @@ -388,7 +388,7 @@ private async Task> TryGetTemplatesInPackAsync(I return scanResult.Templates.Select(t => new TemplateSearchData(t.ToITemplateInfo(), t.ProduceAdditionalData(additionalDataProducers, environmentSettings))); } - return Array.Empty(); + return []; } catch (TaskCanceledException) { @@ -397,7 +397,7 @@ private async Task> TryGetTemplatesInPackAsync(I catch (Exception ex) { Console.WriteLine("Failed to read package {0}::{1}, details: {2}. The package will be skipped.", packInfo.Name, packInfo.Version, ex); - return Array.Empty(); + return []; } } @@ -408,19 +408,19 @@ private async Task> TryGetTemplatesInPackAsync(I List removedTemplatePacks = new List(); List removedNonTemplatePacks = new List(); - foreach (var package in _existingCache.Keys) + foreach (var item in _existingCache) { - if (!newCache.ContainsKey(package)) + if (!newCache.ContainsKey(item.Key)) { - removedTemplatePacks.Add(_existingCache[package]); + removedTemplatePacks.Add(item.Value); } } - foreach (var package in _knownFilteredPackages.Keys) + foreach (var item in _knownFilteredPackages) { - if (!filteredPackages.ContainsKey(package)) + if (!filteredPackages.ContainsKey(item.Key)) { - removedNonTemplatePacks.Add(_knownFilteredPackages[package]); + removedNonTemplatePacks.Add(item.Value); } } if (removedTemplatePacks.Any()) diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/LegacyBlobTemplateInfo.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/LegacyBlobTemplateInfo.cs index 08b0ee29eab..1c72bea3627 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/LegacyBlobTemplateInfo.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/LegacyBlobTemplateInfo.cs @@ -82,7 +82,7 @@ public LegacyBlobTemplateInfo(ITemplateInfo templateInfo) public IReadOnlyList Classifications { get; private set; } [JsonProperty] - public string? DefaultName => string.Empty; + public string DefaultName => string.Empty; [JsonProperty] public string? Description { get; private set; } @@ -103,7 +103,7 @@ public LegacyBlobTemplateInfo(ITemplateInfo templateInfo) public string Name { get; private set; } [JsonIgnore] - public bool PreferDefaultName { get; private set; } + public bool PreferDefaultName { get; } [JsonProperty] public string ShortName @@ -139,13 +139,13 @@ public string ShortName public Guid LocaleConfigMountPointId => Guid.Empty; [JsonProperty] - public string? LocaleConfigPlace => string.Empty; + public string LocaleConfigPlace => string.Empty; [JsonProperty] public Guid HostConfigMountPointId => Guid.Empty; [JsonProperty] - public string? HostConfigPlace => string.Empty; + public string HostConfigPlace => string.Empty; [JsonProperty] public string? ThirdPartyNotices { get; private set; } @@ -160,10 +160,10 @@ public string ShortName public DateTime? ConfigTimestampUtc { get; private set; } [JsonIgnore] - public IReadOnlyDictionary TagsCollection { get; private set; } + public IReadOnlyDictionary TagsCollection { get; } [JsonIgnore] - public IParameterDefinitionSet ParameterDefinitions { get; private set; } + public IParameterDefinitionSet ParameterDefinitions { get; } [JsonIgnore] [Obsolete("Use ParameterDefinitionSet instead.")] @@ -179,7 +179,7 @@ public string ShortName public IReadOnlyDictionary CacheParameters { get; private set; } = new Dictionary(); [JsonIgnore] - public IReadOnlyList PostActions { get; private set; } + public IReadOnlyList PostActions { get; } [JsonIgnore] IReadOnlyList ITemplateMetadata.Constraints => throw new NotImplementedException(); @@ -245,7 +245,7 @@ public BlobLegacyCacheParameter(string? description, string? dataType, string? d public string? DefaultIfOptionWithoutValue { get; } [JsonIgnore] - public string? DisplayName => throw new NotImplementedException(); + public string DisplayName => throw new NotImplementedException(); } } } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/UnifiedPackCheckResultReportWriter.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/UnifiedPackCheckResultReportWriter.cs index acf2a2dce64..c849f42231d 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/UnifiedPackCheckResultReportWriter.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Results/UnifiedPackCheckResultReportWriter.cs @@ -48,7 +48,8 @@ private static void WriteSearchMetadata(PackSourceCheckResult packSourceCheckRes private static void WriteNonTemplatePackList(string reportPath, IReadOnlyList packCheckResults) { - string serializedContent = JsonConvert.SerializeObject(packCheckResults, Formatting.None); + var orderedFilters = packCheckResults.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + string serializedContent = JsonConvert.SerializeObject(orderedFilters, Formatting.None); string outputFileName = Path.Combine(reportPath, NonTemplatePacksFileName); File.WriteAllText(outputFileName, serializedContent); Console.WriteLine($"Non template pack list was created: {outputFileName}"); diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs index 44ad8810480..342e2298e27 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TemplateDiscoveryCommand.cs @@ -116,7 +116,7 @@ public TemplateDiscoveryCommand() : base("template-discovery", "Generates the te DontFilterOnTemplateJson = parseResult.GetValue(_noTemplateJsonFilterOption), Verbose = parseResult.GetValue(_verboseOption), TestEnabled = parseResult.GetValue(_testOption), - Queries = parseResult.GetValue(_queriesOption) ?? Array.Empty(), + Queries = parseResult.GetValue(_queriesOption) ?? [], DiffMode = parseResult.GetValue(_diffOption), DiffOverrideSearchCacheLocation = parseResult.GetValue(_diffOverrideCacheOption), DiffOverrideKnownPackagesLocation = parseResult.GetValue(_diffOverrideNonPackagesOption), diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs index 9e111a587aa..d2e2759385c 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/Test/CacheFileTests.cs @@ -11,36 +11,9 @@ internal static class CacheFileTests { internal static void RunTests(string metadataPath, string legacyMetadataPath) { - //3.1 - string sdkVersion = "3.1.400"; - Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - string workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "3."); - CanSearchWhileInstantiating(workingDirectory, legacyMetadataPath); - CanCheckUpdates(workingDirectory, legacyMetadataPath); - CanUpdate(workingDirectory, legacyMetadataPath); - - //5.0 - sdkVersion = "5.0.100"; - Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "5.0.1", rollForward: "latestPatch"); - CanSearchWhileInstantiating(workingDirectory, legacyMetadataPath); - CanCheckUpdates(workingDirectory, legacyMetadataPath); - CanUpdate(workingDirectory, legacyMetadataPath); - - //5.0.400 - sdkVersion = "5.0.400"; - Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); - workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); - UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "5.0.4", rollForward: "latestPatch"); - CanSearch(workingDirectory, legacyMetadataPath); - CanCheckUpdates(workingDirectory, legacyMetadataPath); - CanUpdate(workingDirectory, legacyMetadataPath); - //6.0.100 - sdkVersion = "6.0.100"; - workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); + string sdkVersion = "6.0.100"; + string workingDirectory = TestUtils.CreateTemporaryFolder(sdkVersion); UseSdkVersion(workingDirectory, requestedSdkVersion: sdkVersion, resolvedVersionPattern: "6.0.1", rollForward: "latestPatch"); Console.WriteLine($"Running tests on .NET {sdkVersion} for: {legacyMetadataPath}."); CanSearch(workingDirectory, legacyMetadataPath); diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackCheckerFactory.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackCheckerFactory.cs index 2bf9ddcbf47..852d9b2f23c 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackCheckerFactory.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackCheckerFactory.cs @@ -48,12 +48,10 @@ public Task CreatePackSourceCheckerAsync(CommandArgs config, FileInfo? fileLocation = config.DiffOverrideKnownPackagesLocation; Verbose.WriteLine($"Opening {fileLocation.FullName}"); - using (var fileStream = fileLocation.OpenRead()) - using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) - using (var jsonReader = new JsonTextReader(textReader)) - { - return new JsonSerializer().Deserialize>(jsonReader); - } + using var fileStream = fileLocation.OpenRead(); + using var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true); + using var jsonReader = new JsonTextReader(textReader); + return new JsonSerializer().Deserialize>(jsonReader); } private static TemplateSearchCache? LoadExistingCache(CommandArgs config) @@ -65,12 +63,10 @@ public Task CreatePackSourceCheckerAsync(CommandArgs config, FileInfo? cacheFileLocation = config.DiffOverrideSearchCacheLocation; Verbose.WriteLine($"Opening {cacheFileLocation.FullName}"); - using (var fileStream = cacheFileLocation.OpenRead()) - using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) - using (var jsonReader = new JsonTextReader(textReader)) - { - return TemplateSearchCache.FromJObject(JObject.Load(jsonReader), NullLogger.Instance, new Dictionary>() { { CliHostSearchCacheData.DataName, CliHostSearchCacheData.Reader } }); - } + using var fileStream = cacheFileLocation.OpenRead(); + using var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true); + using var jsonReader = new JsonTextReader(textReader); + return TemplateSearchCache.FromJObject(JObject.Load(jsonReader), NullLogger.Instance, new Dictionary>() { { CliHostSearchCacheData.DataName, CliHostSearchCacheData.Reader } }); } } } diff --git a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackProvider.cs b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackProvider.cs index fab348120d4..f2fd334ac6b 100644 --- a/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackProvider.cs +++ b/tools/Microsoft.TemplateSearch.TemplateDiscovery/TestProvider/TestPackProvider.cs @@ -90,9 +90,9 @@ internal TestPackInfo(string path) public bool Reserved => false; - public string? Description => "description"; + public string Description => "description"; - public string? IconUrl => "https://icon"; + public string IconUrl => "https://icon"; } } } diff --git a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/ArgumentEscaper.cs b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/ArgumentEscaper.cs index 3d85abf4b4f..eb0d24b4045 100644 --- a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/ArgumentEscaper.cs +++ b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/ArgumentEscaper.cs @@ -106,13 +106,13 @@ internal static bool ShouldSurroundWithQuotes(string argument) internal static bool IsSurroundedWithQuotes(string argument) { - return argument.StartsWith("\"", StringComparison.Ordinal) && - argument.EndsWith("\"", StringComparison.Ordinal); + return argument.StartsWith('"') && + argument.EndsWith('"'); } internal static bool ArgumentContainsWhitespace(string argument) { - return argument.Contains(" ") || argument.Contains("\t") || argument.Contains("\n"); + return argument.Contains(' ') || argument.Contains('\t') || argument.Contains('\n'); } /// diff --git a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/NativeMethods.cs b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/NativeMethods.cs index aff6d99e622..83d3d50cbcd 100644 --- a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/NativeMethods.cs +++ b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/NativeMethods.cs @@ -72,21 +72,10 @@ internal struct JobObjectExtendedLimitInformation public UIntPtr PeakJobMemoryUsed; } - [StructLayout(LayoutKind.Sequential)] - internal struct PROCESS_BASIC_INFORMATION - { - public uint ExitStatus; - public IntPtr PebBaseAddress; - public UIntPtr AffinityMask; - public int BasePriority; - public UIntPtr UniqueProcessId; - public UIntPtr InheritedFromUniqueProcessId; - } } internal static class Posix { - internal const int SIGINT = 2; internal const int SIGTERM = 15; [DllImport("libc", SetLastError = true)] diff --git a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/StreamForwarder.cs b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/StreamForwarder.cs index 4851959c7ba..dfe1ff6567f 100644 --- a/tools/Shared/Microsoft.TemplateEngine.CommandUtils/StreamForwarder.cs +++ b/tools/Shared/Microsoft.TemplateEngine.CommandUtils/StreamForwarder.cs @@ -8,7 +8,7 @@ namespace Microsoft.TemplateEngine.CommandUtils internal sealed class StreamForwarder { private const char FlushBuilderCharacter = '\n'; - private static readonly char[] IgnoreCharacters = new char[] { '\r' }; + private const char CarriageReturn = '\r'; private StringBuilder? _builder; private StringWriter? _capture; @@ -69,7 +69,7 @@ public void Read(TextReader reader) { WriteBuilder(); } - else if (!IgnoreCharacters.Contains(currentCharacter)) + else if (currentCharacter != CarriageReturn) { _ = _builder.Append(currentCharacter); } diff --git a/tools/legacy-tools/AcquireDotnet.ps1 b/tools/legacy-tools/AcquireDotnet.ps1 deleted file mode 100644 index f00ca462f71..00000000000 --- a/tools/legacy-tools/AcquireDotnet.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -$RepoRoot = "$PSScriptRoot\.." -$ArtifactsDir = "$RepoRoot\artifacts" - -if(!(Test-Path -Path $ArtifactsDir)) { - mkdir $ArtifactsDir | Out-Null -} - -# Use a repo-local install directory (but not the artifacts directory because that gets cleaned a lot -if (!$env:DOTNET_INSTALL_DIR) -{ - $env:DOTNET_INSTALL_DIR="$RepoRoot\.dotnet\" -} - -if (!(Test-Path $env:DOTNET_INSTALL_DIR)) -{ - mkdir $env:DOTNET_INSTALL_DIR | Out-Null -} - -$DOTNET_INSTALL_SCRIPT_URL="https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1" -Invoke-WebRequest $DOTNET_INSTALL_SCRIPT_URL -OutFile "$RepoRoot\artifacts\dotnet-install.ps1" - -& "$RepoRoot\artifacts\dotnet-install.ps1" -Version 2.1.400-preview-009063 -if($LASTEXITCODE -ne 0) { throw "Failed to install dotnet cli" } - -# Put the stage0 on the path -$env:PATH = "$env:DOTNET_INSTALL_DIR;$env:PATH" diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer.sln b/tools/legacy-tools/BaselineComparer/BaselineComparer.sln deleted file mode 100644 index ea53d190151..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27120.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaselineComparer", "BaselineComparer\BaselineComparer.csproj", "{A8DC5F3C-D6A3-4E31-AC8E-C9D5E6DD940E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaselineComparerTests", "BaselineComparerTests\BaselineComparerTests.csproj", "{6A036613-C79A-4070-B490-8EE4E372FA4B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A8DC5F3C-D6A3-4E31-AC8E-C9D5E6DD940E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A8DC5F3C-D6A3-4E31-AC8E-C9D5E6DD940E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A8DC5F3C-D6A3-4E31-AC8E-C9D5E6DD940E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A8DC5F3C-D6A3-4E31-AC8E-C9D5E6DD940E}.Release|Any CPU.Build.0 = Release|Any CPU - {6A036613-C79A-4070-B490-8EE4E372FA4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6A036613-C79A-4070-B490-8EE4E372FA4B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6A036613-C79A-4070-B490-8EE4E372FA4B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6A036613-C79A-4070-B490-8EE4E372FA4B}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {82C88E50-9178-44D9-B41C-4DBF22AC9A1A} - EndGlobalSection -EndGlobal diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCommandData.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCommandData.cs deleted file mode 100644 index 00353a2e012..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCommandData.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - public class BaselineCommandData - { - public string Command { get; set; } - public string RelativePath { get; set; } - public string ReportFileName { get; set; } - - public static BaselineCommandData FromJObject(JObject source) - { - return new BaselineCommandData() - { - Command = source.GetValue(nameof(Command)).ToString(), - RelativePath = source.GetValue(nameof(RelativePath)).ToString(), - ReportFileName = source.GetValue(nameof(ReportFileName)).ToString() - }; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineComparer.csproj b/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineComparer.csproj deleted file mode 100644 index 35fcb33162d..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineComparer.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - Exe - $(NETCoreTargetFramework) - - - - - - - - diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCreator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCreator.cs deleted file mode 100644 index 62e12df1ef7..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineCreator.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace BaselineComparer -{ - public class BaselineCreator - { - public static readonly string BaseDataDir = "Data"; - public static readonly string BaseReportDir = "BaselineReports"; - public static readonly string BaselineMasterDataDirName = "BaselineMaster"; - private static readonly string BaselineSecondaryDataDirName = "BaselineSecondary"; - - public BaselineCreator(string baselineRoot, string newCommand, IReadOnlyList invocationUnits) - { - BaselineRoot = baselineRoot; - NewCommand = newCommand; - string dataDir = Path.Combine(BaselineRoot, BaseDataDir); - _masterDataBasePath = Path.Combine(dataDir, BaselineMasterDataDirName); - _secondaryDataBasePath = Path.Combine(dataDir, BaselineSecondaryDataDirName); - - _reportDir = Path.Combine(BaselineRoot, BaseReportDir); - _invocationUnits = invocationUnits; - } - - public string BaselineRoot { get; } - public string NewCommand { get; } - - private readonly string _masterDataBasePath; - private readonly string _secondaryDataBasePath; - private readonly string _reportDir; - - private readonly IReadOnlyList _invocationUnits; - // unit name -> command -> relative path - private IReadOnlyDictionary> _unitNameAndCommandToDataPathMap; - private IReadOnlyDictionary> _unitNameAndCommandToReportFileMap; - - public void CreateBaseline() - { - AssignRelativePathsAndReportNamesToCommands(); - - if (!TryCreateTemplates()) - { - throw new Exception("There were problems creating the templates to compare."); - } - - BaselineReportCreator reportCreator = new BaselineReportCreator(_masterDataBasePath, _secondaryDataBasePath, _invocationUnits, _unitNameAndCommandToDataPathMap, _unitNameAndCommandToReportFileMap); - reportCreator.WriteAllBaselineComparisons(_reportDir, NewCommand); - } - - // todo: move this outside this class for creating comparison data. - private bool TryCreateTemplates() - { - bool allCreationsGood = true; - - foreach (InvocationUnit unit in _invocationUnits) - { - CustomHiveCoordinator hive = new CustomHiveCoordinator(NewCommand, unit.InstallRequirements); - hive.InitializeHive(); - - IReadOnlyDictionary commandToPathMap = _unitNameAndCommandToDataPathMap[unit.Name]; - allCreationsGood &= hive.TryCreateTemplateData(_masterDataBasePath, commandToPathMap); - allCreationsGood &= hive.TryCreateTemplateData(_secondaryDataBasePath, commandToPathMap); - - hive.DeleteHive(); - } - - return allCreationsGood; - } - - private void AssignRelativePathsAndReportNamesToCommands() - { - Dictionary> unitCommandDataPaths = new Dictionary>(); - Dictionary> unitCommandReportFiles = new Dictionary>(); - - foreach (InvocationUnit unit in _invocationUnits) - { - int commandIndex = 0; - - if (unitCommandDataPaths.ContainsKey(unit.Name)) - { - throw new Exception($"Multiple invocation units with the same name are not allowed. Duplicated name: '{unit.Name}'"); - } - - Dictionary commandToDataPathMap = new Dictionary(); - unitCommandDataPaths[unit.Name] = commandToDataPathMap; - Dictionary commandToReportFileMap = new Dictionary(); - unitCommandReportFiles[unit.Name] = commandToReportFileMap; - - foreach (string command in unit.InvocationCommands) - { - commandToDataPathMap[command] = Guid.NewGuid().ToString(); - commandToReportFileMap[command] = $"{unit.Name}_{commandIndex}.json"; - ++commandIndex; - } - } - - _unitNameAndCommandToDataPathMap = unitCommandDataPaths; - _unitNameAndCommandToReportFileMap = unitCommandReportFiles; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineMasterReport.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineMasterReport.cs deleted file mode 100644 index d80bdd1d430..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineMasterReport.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - // The master baseline file from a set of invocation units - public class BaselineMasterReport - { - [JsonProperty] - public string NewCommand { get; set; } - - [JsonProperty] - public IReadOnlyList Invocations { get; set; } - - public static BaselineMasterReport FromFile(string filename) - { - string fileContent; - - try - { - fileContent = File.ReadAllText(filename); - } - catch (Exception ex) - { - Console.WriteLine($"Unable to read the specified baseline file: {filename}"); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - - BaselineMasterReport baselineMasterReport; - - try - { - JObject baselineJObject = JObject.Parse(fileContent); - baselineMasterReport = FromJObject(baselineJObject); - return baselineMasterReport; - } - catch (Exception ex) - { - Console.WriteLine($"Unable to deserialize the existing baseline data file: {filename}."); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - } - - public static BaselineMasterReport FromJObject(JObject source) - { - string newCommand = source.GetValue(nameof(NewCommand)).ToString(); - - List invocationUnitList = new List(); - - foreach (JToken unitJObject in source.GetValue(nameof(Invocations))) - { - InvocationBaselineUnit invocationUnit = InvocationBaselineUnit.FromJObject((JObject)unitJObject); - invocationUnitList.Add(invocationUnit); - } - - return new BaselineMasterReport() - { - NewCommand = newCommand, - Invocations = invocationUnitList - }; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineReportCreator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineReportCreator.cs deleted file mode 100644 index 943e499aa25..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BaselineReportCreator.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using BaselineComparer.TemplateComparison; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - public class BaselineReportCreator - { - public static readonly string MasterBaselineReportFileName = "Baseline.json"; - - public BaselineReportCreator(string masterDataBasePath, string secondaryDataBasePath, IReadOnlyList invocationUnits, IReadOnlyDictionary> unitNameAndCommandToDataPathMap, IReadOnlyDictionary> unitNameAndCommandToReportFileMap) - { - _masterDataBasePath = masterDataBasePath; - _secondaryDataBasePath = secondaryDataBasePath; - _invocationUnits = invocationUnits; - _unitNameAndCommandToDataPathMap = unitNameAndCommandToDataPathMap; - _unitNameAndCommandToReportFileMap = unitNameAndCommandToReportFileMap; - } - - private readonly string _masterDataBasePath; - private readonly string _secondaryDataBasePath; - private readonly IReadOnlyList _invocationUnits; - private readonly IReadOnlyDictionary> _unitNameAndCommandToDataPathMap; - private readonly IReadOnlyDictionary> _unitNameAndCommandToReportFileMap; - - public void WriteAllBaselineComparisons(string reportDir, string newCommand) - { - if (!Directory.Exists(reportDir)) - { - Directory.CreateDirectory(reportDir); - } - - // write the comparisons for the commands - List invocationBaselineUnitList = new List(); - - foreach (InvocationUnit unit in _invocationUnits) - { - IReadOnlyList unitCommandData = WriteBaselineComparisonsForInvocationUnit(unit, reportDir, newCommand); - InvocationBaselineUnit reportUnit = new InvocationBaselineUnit(unit.Name, unit.InstallRequirements, unitCommandData); - invocationBaselineUnitList.Add(reportUnit); - } - - // write the master baseline report. - BaselineMasterReport masterBaseline = new BaselineMasterReport() - { - NewCommand = newCommand, - Invocations = invocationBaselineUnitList - }; - JObject serializedMaster = JObject.FromObject(masterBaseline); - - string masterBaselineReportFilename = Path.Combine(reportDir, MasterBaselineReportFileName); - File.WriteAllText(masterBaselineReportFilename, serializedMaster.ToString()); - } - - private IReadOnlyList WriteBaselineComparisonsForInvocationUnit(InvocationUnit unit, string reportDir, string newCommand) - { - if (!_unitNameAndCommandToDataPathMap.TryGetValue(unit.Name, out IReadOnlyDictionary commandToDataRelativePathMap)) - { - throw new Exception($"Invocation unit {unit.Name} didn't have a command-path map"); - } - - if (!_unitNameAndCommandToReportFileMap.TryGetValue(unit.Name, out IReadOnlyDictionary commandToReportFileMap)) - { - throw new Exception($"Invocation unit {unit.Name} didn't have a report file map"); - } - - IReadOnlyDictionary comparisonsForUnit = CreateComparisonsForInvocationUnit(commandToDataRelativePathMap); - List commandInfoList = new List(); - - foreach (KeyValuePair commandComparison in comparisonsForUnit) - { - string command = commandComparison.Key; - if (!commandToDataRelativePathMap.TryGetValue(command, out string relativePath)) - { - throw new Exception($"Unit '{unit.Name}' data map didnt have a data path for command: '{command}'"); - } - - CommandBaseline baselineForCommand = new CommandBaseline() - { - InvocationName = unit.Name, - Command = command, - NewCommand = newCommand, - FileResults = commandComparison.Value - }; - - if (!commandToReportFileMap.TryGetValue(command, out string reportFilename)) - { - throw new Exception($"Unit '{unit.Name}' report map didnt have a report file for command: '{command}'"); - } - - string reportFileFullPath = Path.Combine(reportDir, reportFilename); - JObject serialized = JObject.FromObject(baselineForCommand); - - File.WriteAllText(reportFileFullPath, serialized.ToString()); - - BaselineCommandData dataForCommand = new BaselineCommandData() - { - Command = command, - RelativePath = relativePath, - ReportFileName = reportFilename - }; - commandInfoList.Add(dataForCommand); - } - - return commandInfoList; - } - - private IReadOnlyDictionary CreateComparisonsForInvocationUnit(IReadOnlyDictionary commandAndPathMap) - { - Dictionary comparisonResults = new Dictionary(); - - foreach (KeyValuePair commandAndRelativePath in commandAndPathMap) - { - string command = commandAndRelativePath.Key; - string relativePath = commandAndRelativePath.Value; - - DirectoryComparer comparer = new DirectoryComparer(_masterDataBasePath, _secondaryDataBasePath, relativePath); - comparisonResults[command] = comparer.Compare(); - } - - return comparisonResults; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/BufferedReadStream.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/BufferedReadStream.cs deleted file mode 100644 index 3b082ca8c6b..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/BufferedReadStream.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; -using System.IO; - -namespace BaselineComparer -{ - public class BufferedReadStream - { - private static readonly int _readBlockSize = 1000; - - private readonly Stream _source; - private int _readBlockNumber; - private int _positionInBuffer; - private byte[] _buffer; - - private bool _finalReadBlock; - private int _endIfFinalReadBlock; - - public BufferedReadStream(Stream source) - { - _source = source; - _readBlockNumber = -1; - _positionInBuffer = 0; - _buffer = new byte[_readBlockSize]; - - _finalReadBlock = false; - _endIfFinalReadBlock = -1; - - _inReplayMode = false; - - ReadNextBlock(); - } - - private bool _inReplayMode; - private int _replayIndex; - private byte[] _replayBuffer; - private int _replayStartPosition; - - public void SetupReplayBytes(byte[] toReplay) - { - if (_inReplayMode) - { - throw new Exception("Cant setup nested replays"); - } - - _replayStartPosition = LastReadPosition - toReplay.Length; - _replayIndex = 0; - _replayBuffer = (byte[])toReplay.Clone(); - _inReplayMode = true; - } - - public bool TryReadNext(out byte next) - { - if (_inReplayMode) - { - if (_replayIndex == _replayBuffer.Length) - { - _inReplayMode = false; - } - else - { - next = _replayBuffer[_replayIndex]; - ++_replayIndex; - return true; - } - } - - if (_positionInBuffer >= _readBlockSize) - { - ReadNextBlock(); - } - - if (_finalReadBlock && _positionInBuffer >= _endIfFinalReadBlock) - { - next = 0; - return false; - } - - next = _buffer[_positionInBuffer++]; - return true; - } - - public byte[] ReadBytes(int toReadCount, out int actuallyReadCount) - { - byte[] tryReadBuffer = new byte[toReadCount]; - actuallyReadCount = 0; - - for (int i = 0; i < toReadCount; i++) - { - if (TryReadNext(out byte next)) - { - tryReadBuffer[i] = next; - } - else - { - break; - } - - ++actuallyReadCount; - } - - Span actuallyReadBuffer = tryReadBuffer; - return actuallyReadBuffer.Slice(0, actuallyReadCount).ToArray(); - } - - public int LastReadPosition - { - get - { - if (_inReplayMode) - { - return _replayStartPosition + _replayIndex; - } - - return _readBlockNumber * _readBlockSize + _positionInBuffer; - } - } - - public bool DoneReading - { - get - { - return _finalReadBlock && _positionInBuffer >= _endIfFinalReadBlock; - } - } - - private void ReadNextBlock() - { - Array.Clear(_buffer, 0, _readBlockSize); - int byteCount = _source.Read(_buffer, 0, _readBlockSize); - - if (byteCount < _readBlockSize) - { - _finalReadBlock = true; - _endIfFinalReadBlock = byteCount; - } - - _positionInBuffer = 0; - ++_readBlockNumber; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/CommandBaseline.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/CommandBaseline.cs deleted file mode 100644 index 1d8ef418167..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/CommandBaseline.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.IO; -using BaselineComparer.TemplateComparison; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - public class CommandBaseline - { - [JsonProperty] - public string InvocationName { get; set; } - - [JsonProperty] - public string Command { get; set; } - - [JsonProperty] - public string NewCommand { get; set; } - - [JsonProperty] - public DirectoryDifference FileResults { get; set; } - - public static CommandBaseline FromFile(string filename) - { - string fileContent; - - try - { - fileContent = File.ReadAllText(filename); - } - catch (Exception ex) - { - Console.WriteLine($"Unable to read the specified command baseline file: {filename}"); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - - CommandBaseline differenceReport; - - try - { - JObject reportJObject = JObject.Parse(fileContent); - differenceReport = FromJObject(reportJObject); - return differenceReport; - } - catch (Exception ex) - { - Console.WriteLine($"Unable to deserialize the existing differce report file: {filename}"); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - } - - public static CommandBaseline FromJObject(JObject source) - { - string invocationName = source.GetValue(nameof(InvocationName)).ToString(); - string command = source.GetValue(nameof(Command)).ToString(); - string newCommand = source.GetValue(nameof(NewCommand)).ToString(); - - JObject directoryDifferenceJObject = (JObject)source.GetValue(nameof(FileResults)); - DirectoryDifference fileResults = DirectoryDifference.FromJObject(directoryDifferenceJObject); - - return new CommandBaseline() - { - InvocationName = invocationName, - Command = command, - NewCommand = newCommand, - FileResults = fileResults - }; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/ComparisonComparisonReportCreator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/ComparisonComparisonReportCreator.cs deleted file mode 100644 index a6ea00976de..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/ComparisonComparisonReportCreator.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using BaselineComparer.DifferenceComparison; -using BaselineComparer.TemplateComparison; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - public class ComparisonComparisonReportCreator - { - private static readonly string BaselineOnlyReportFilename = "BaselineOnlyReports.json"; - private static readonly string ComparisonOnlyReportFilename = "ComparisonOnlyReports.json"; - - public ComparisonComparisonReportCreator(string baselineReportDir, string comparisonReportDir) - { - _baselineReportDir = baselineReportDir; - _comparisonReportDir = comparisonReportDir; - } - - private readonly string _baselineReportDir; - private readonly string _comparisonReportDir; - - private IReadOnlyList _commonReportFiles; - private IReadOnlyList _baselineOnlyFiles; - private IReadOnlyList _comparisonOnlyFiles; - - public void CreateComparisons(string comparisonComparisonReportDir) - { - if (!Directory.Exists(comparisonComparisonReportDir)) - { - Directory.CreateDirectory(comparisonComparisonReportDir); - } - - Console.WriteLine("Generating comparison comparison reports."); - DetermineReportDispositions(); - - CreateCommonFileComparisonReports(comparisonComparisonReportDir); - CreateBaselineOnlyReportReport(comparisonComparisonReportDir); - CreateComparisonOnlyReportReport(comparisonComparisonReportDir); - } - - private void CreateCommonFileComparisonReports(string comparisonComparisonReportDir) - { - foreach (string differenceReportFilename in _commonReportFiles) - { - string baselineReportPath = Path.Combine(_baselineReportDir, differenceReportFilename); - CommandBaseline baselineBaseline = CommandBaseline.FromFile(baselineReportPath); - DirectoryDifference baselineDifference = baselineBaseline.FileResults; - - string comparisonReportPath = Path.Combine(_comparisonReportDir, differenceReportFilename); - CommandBaseline comparisonBaseline = CommandBaseline.FromFile(comparisonReportPath); - DirectoryDifference comparisonDifference = comparisonBaseline.FileResults; - - - DirectoryDifferenceComparer comparer = new DirectoryDifferenceComparer(baselineDifference, comparisonDifference); - DirectoryComparisonDifference comparisonComparison = comparer.Compare(); - StructuredDirectoryComparisonDifference structuredDifference = StructuredDirectoryComparisonDifference.FromDirectoryComparisonDifference(comparisonComparison); - - JObject serialized = JObject.FromObject(structuredDifference); - string comparisonComparisonReportFile = Path.Combine(comparisonComparisonReportDir, differenceReportFilename); - File.WriteAllText(comparisonComparisonReportFile, serialized.ToString()); - } - } - - private void CreateBaselineOnlyReportReport(string comparisonComparisonReportDir) - { - if (_baselineOnlyFiles.Count == 0) - { - return; - } - - string serialized = JsonConvert.SerializeObject(_baselineOnlyFiles); - string reportPath = Path.Combine(comparisonComparisonReportDir, BaselineOnlyReportFilename); - File.WriteAllText(reportPath, serialized); - } - - private void CreateComparisonOnlyReportReport(string comparisonComparisonReportDir) - { - if (_comparisonOnlyFiles.Count == 0) - { - return; - } - - string serialized = JsonConvert.SerializeObject(_comparisonOnlyFiles); - string reportPath = Path.Combine(comparisonComparisonReportDir, ComparisonOnlyReportFilename); - File.WriteAllText(reportPath, serialized); - } - - // Looks at the report files in both directories. Cagegorize them as common vs. just in one or the other dirs. - private void DetermineReportDispositions() - { - HashSet baselineReportFiles = GetReportFileNames(_baselineReportDir); - HashSet comparisonReportFiles = GetReportFileNames(_comparisonReportDir); - - _commonReportFiles = baselineReportFiles.Intersect(comparisonReportFiles).ToList(); - _baselineOnlyFiles = baselineReportFiles.Except(comparisonReportFiles).ToList(); - _comparisonOnlyFiles = comparisonReportFiles.Except(baselineReportFiles).ToList(); - } - - private HashSet GetReportFileNames(string baseDir) - { - return new HashSet(Directory.EnumerateFiles(baseDir, "*.json") - .Select(x => Path.GetFileName(x)) - .Where(x => !string.Equals(x, BaselineReportCreator.MasterBaselineReportFileName))); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/CustomHiveCoordinator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/CustomHiveCoordinator.cs deleted file mode 100644 index a2b90f3d07d..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/CustomHiveCoordinator.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using BaselineComparer.Helpers; - -namespace BaselineComparer -{ - public class CustomHiveCoordinator - { - public CustomHiveCoordinator(string newCommand, IReadOnlyList toInstall) - { - _newCommand = newCommand; - _toInstallList = toInstall; - _customHiveBaseDir = @"c:\temp\" + Guid.NewGuid().ToString() + @"\"; - } - - private readonly string _newCommand; - private readonly IReadOnlyList _toInstallList; - private readonly string _customHiveBaseDir; - - public bool TryCreateTemplateData(string basePath, IReadOnlyDictionary commandToRelativePathMap) - { - bool allCreationGood = true; - - foreach (KeyValuePair commandAndRelativePath in commandToRelativePathMap) - { - string command = commandAndRelativePath.Key; - string relativePath = commandAndRelativePath.Value; - string creationPath = Path.Combine(basePath, relativePath); - allCreationGood &= TemplateCommandRunner.RunTemplateCommand(_newCommand, creationPath, command, _customHiveBaseDir, false); - } - - return allCreationGood; - } - - public void DeleteHive() - { - Directory.Delete(_customHiveBaseDir, true); - } - - public bool InitializeHive() - { - bool anyProblems = TryUninstallAllTemplatesFromHive(); - anyProblems |= TryInstallRequiredPackages(); - - return anyProblems; - } - - // TODO: better detection that uninstalls actually worked (Can't do right now) - private bool TryInstallRequiredPackages() - { - Console.WriteLine("Installing required packages."); - - string installCommandArgs = null; - try - { - foreach (string toInstall in _toInstallList) - { - installCommandArgs = $"{_newCommand} -i {toInstall} --debug:custom-hive {_customHiveBaseDir}"; - Console.WriteLine($"Installing {toInstall} "); - Console.WriteLine($"\t{installCommandArgs}"); - Proc.Run("dotnet", installCommandArgs).WaitForExit(); - } - } - catch (Exception ex) - { - Console.WriteLine($"Failed to install everything for the install unit. Failure occurred with command:"); - Console.WriteLine($"\t{installCommandArgs}"); - Console.WriteLine($"Error: {ex.Message}"); - return false; - } - - return true; - } - - private static readonly string UninstallListHeader = "Currently installed items:"; - - // TODO: better detection that installs actually worked (Can't do right now) - private bool TryUninstallAllTemplatesFromHive() - { - Console.WriteLine("Finding things to uninstall."); - - string uninstallListCommandArgs = $"{_newCommand} -u --debug:custom-hive {_customHiveBaseDir}"; - ProcessEx uninstallListCommand = Proc.Run("dotnet", uninstallListCommandArgs); - uninstallListCommand.WaitForExit(); - - string output = uninstallListCommand.Output; - - string[] outputLineList = output.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); - List toUninstallList = new List(); - - string previousLine = null; - - foreach (string outputLine in outputLineList) - { - if (string.Equals(outputLine.Trim(), "Templates:", StringComparison.Ordinal) - && !string.IsNullOrEmpty(previousLine)) - { - toUninstallList.Add(previousLine); - Console.WriteLine($"adding to uninstall list: {previousLine}"); - } - - previousLine = outputLine; - } - - Console.WriteLine("Uninstalling everything."); - - try - { - foreach (string toUninstall in toUninstallList) - { - string uninstallArgs = $"{_newCommand} -u {toUninstall} --debug:custom-hive {_customHiveBaseDir}"; - Console.WriteLine($"Uninstalling {toUninstall}"); - Console.WriteLine($"Uninstall command args: {uninstallArgs}"); - Proc.Run("dotnet", uninstallArgs).WaitForExit(); - } - } - catch (Exception ex) - { - Console.WriteLine($"Failed to uninstall everything for custom hive {_customHiveBaseDir}"); - Console.WriteLine($"Error: {ex.Message}"); - return false; - } - - return true; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryComparisonDifference.cs deleted file mode 100644 index 744433db1d6..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryComparisonDifference.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace BaselineComparer.DifferenceComparison -{ - public class DirectoryComparisonDifference - { - public DirectoryComparisonDifference() - { - _fileResults = new List(); - } - - private List _fileResults; - private bool _invalidSecondaryData; - private bool _invalidBaselineData; - - public IReadOnlyList FileResults => _fileResults; - - public void AddFileResult(FileComparisonDifference fileComparison) - { - _fileResults.Add(fileComparison); - } - - public bool InvalidBaselineData - { - get - { - return _invalidBaselineData; - } - set - { - if (_fileResults.Count > 0) - { - throw new Exception("Cant have comparisons if the baseline is invalid."); - } - - _invalidBaselineData = value; - } - } - - public bool InvalidSecondaryData - { - get - { - return _invalidSecondaryData; - } - set - { - if (_fileResults.Count > 0) - { - throw new Exception("Cant have comparisons if the secondary data is invalid."); - } - - _invalidSecondaryData = value; - } - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryDifferenceComparer.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryDifferenceComparer.cs deleted file mode 100644 index c472c9ea0cc..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/DirectoryDifferenceComparer.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using BaselineComparer.TemplateComparison; - -namespace BaselineComparer.DifferenceComparison -{ - public class DirectoryDifferenceComparer - { - public DirectoryDifferenceComparer(DirectoryDifference baselineDifference, DirectoryDifference checkDifference) - { - BaselineDifference = baselineDifference; - CheckDifference = checkDifference; - } - - public DirectoryDifference BaselineDifference { get; } - - public DirectoryDifference CheckDifference { get; } - - public DirectoryComparisonDifference Compare() - { - DirectoryComparisonDifference comparisonResult = new DirectoryComparisonDifference(); - - if (!BaselineDifference.IsValidBaseline) - { - comparisonResult.InvalidBaselineData = true; - return comparisonResult; - } - - if (!CheckDifference.IsValidBaseline) - { - comparisonResult.InvalidSecondaryData = true; - return comparisonResult; - } - - IReadOnlyDictionary checkFileLookup = CheckDifference.FileResults.ToDictionary(x => x.File, x => x); - - foreach (FileDifference baselineFileDiff in BaselineDifference.FileResults) - { - if (!checkFileLookup.TryGetValue(baselineFileDiff.File, out FileDifference checkFileDiff)) - { - FileComparisonDifference fileResult = new FileComparisonDifference(baselineFileDiff.File); - fileResult.MissingSecondaryFile = true; - comparisonResult.AddFileResult(fileResult); - } - else - { - FileDifferenceComparer comparer = new FileDifferenceComparer(baselineFileDiff, checkFileDiff); - FileComparisonDifference fileResult = comparer.Compare(); - comparisonResult.AddFileResult(fileResult); - } - } - - // check for files in the check result but not the baseline. - HashSet baselineFileLookup = new HashSet(BaselineDifference.FileResults.Select(x => x.File)); - foreach (FileDifference checkFileDifference in CheckDifference.FileResults) - { - if (!baselineFileLookup.Contains(checkFileDifference.File)) - { - FileComparisonDifference fileResult = new FileComparisonDifference(checkFileDifference.File); - fileResult.MissingBaselineFile = true; - comparisonResult.AddFileResult(fileResult); - } - } - - return comparisonResult; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileComparisonDifference.cs deleted file mode 100644 index c27ccdd8732..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileComparisonDifference.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using BaselineComparer.TemplateComparison; - -namespace BaselineComparer.DifferenceComparison -{ - public class FileComparisonDifference - { - public FileComparisonDifference(string filename) - { - Filename = filename; - _positionallyMatchedDifferences = new List(); - _baselineOnlyDifferences = new List(); - _checkOnlyDifferences = new List(); - } - - public string Filename { get; } - - private List _positionallyMatchedDifferences; - private List _baselineOnlyDifferences; - private List _checkOnlyDifferences; - private bool _missingBaselineFile; - private bool _missingSecondaryFile; - - // Stores the differences that positionally match up between two sets of comparisons. - // They could still have a datatype or length mismatch. - // The key is the baseline difference, the value is the difference for the current comparison. - public IReadOnlyList PositionallyMatchedDifferences => _positionallyMatchedDifferences; - - // Differences from the baseline comparison that couldn't be matched to differences from the check comparison. - public IReadOnlyList BaselineOnlyDifferences => _baselineOnlyDifferences; - - // Differences from the check comparison that couldn't be matched to differences from the baseline comparison. - public IReadOnlyList SecondaryOnlyDifferences => _checkOnlyDifferences; - - public void AddPositionallyMatchedDifference(PositionalDifference baselineDifference, PositionalDifference checkDifference, PositionalComparisonDisposition disposition) - { - _positionallyMatchedDifferences.Add(new PositionalComparisonDifference(baselineDifference, checkDifference, disposition)); - } - - public void AddBaselineOnlyDifference(PositionalDifference baselineDifference) - { - if (MissingBaselineFile || MissingSecondaryFile) - { - throw new System.Exception("Cant have differences if a file is missing."); - } - - _baselineOnlyDifferences.Add(baselineDifference); - } - - public void AddCheckOnlyDifference(PositionalDifference checkDifference) - { - if (MissingBaselineFile || MissingSecondaryFile) - { - throw new System.Exception("Cant have differences if a file is missing."); - } - - _checkOnlyDifferences.Add(checkDifference); - } - - // externally set in situations where the number of classified differences don't exactly match the number of original differences. - public bool HasDifferenceResolutionError { get; set; } - - public bool AnyInvalidDifferences - { - get - { - return BaselineOnlyDifferences.Count > 0 - || SecondaryOnlyDifferences.Count > 0 - || MissingBaselineFile - || MissingSecondaryFile - || PositionallyMatchedDifferences.Any(d => d.Disposition != PositionalComparisonDisposition.Match); - } - } - - public bool MissingBaselineFile - { - get - { - return _missingBaselineFile; - } - set - { - if (_positionallyMatchedDifferences.Count > 0 - || _baselineOnlyDifferences.Count > 0 - || _checkOnlyDifferences.Count > 0) - { - throw new System.Exception("Cant label baseline file as missing - there are registered differences."); - } - - _missingBaselineFile = value; - } - } - - public bool MissingSecondaryFile - { - get - { - return _missingSecondaryFile; - } - set - { - if (_positionallyMatchedDifferences.Count > 0 - || _baselineOnlyDifferences.Count > 0 - || _checkOnlyDifferences.Count > 0) - { - throw new System.Exception("Cant label secondary file as missing - there are registered differences."); - } - - _missingSecondaryFile = value; - } - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileDifferenceComparer.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileDifferenceComparer.cs deleted file mode 100644 index 3e43f0c9e15..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/FileDifferenceComparer.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using BaselineComparer.TemplateComparison; - -namespace BaselineComparer.DifferenceComparison -{ - public class FileDifferenceComparer - { - public FileDifferenceComparer(FileDifference baselineComparisonDifferences, FileDifference checkComparisonDifferences) - { - BaselineComparisonDifferences = baselineComparisonDifferences; - CheckComparisonDifferences = checkComparisonDifferences; - } - - public FileDifference BaselineComparisonDifferences { get; } - - public FileDifference CheckComparisonDifferences { get; } - - public FileComparisonDifference Compare() - { - int baselineDiffIndex = 0; - int checkDiffIndex = 0; - FileComparisonDifference fileResult = new FileComparisonDifference(BaselineComparisonDifferences.File); - - while (baselineDiffIndex < BaselineComparisonDifferences.Differences.Count && checkDiffIndex < CheckComparisonDifferences.Differences.Count) - { - PositionalDifference baselineDiff = BaselineComparisonDifferences.Differences[baselineDiffIndex]; - PositionalDifference checkDiff = CheckComparisonDifferences.Differences[checkDiffIndex]; - - if (Math.Abs(baselineDiff.BaselineStartPosition - checkDiff.BaselineStartPosition) > baselineDiff.LocationLeeway) - { - // The differences are too far apart in absolute baseline position, it's a non-match. Consume the first one. - // Once one of these occurs, the overall match has failed, and the rest will probably be bad too. - if (baselineDiff.BaselineStartPosition < checkDiff.BaselineStartPosition) - { - fileResult.AddBaselineOnlyDifference(baselineDiff); - ++baselineDiffIndex; - } - else - { - fileResult.AddCheckOnlyDifference(checkDiff); - ++checkDiffIndex; - } - } - else - { - // the differences are close enough to compare to each other. - if (baselineDiff.Classification != checkDiff.Classification) - { - // The classifications are different, it's a non-match - fileResult.AddPositionallyMatchedDifference(baselineDiff, checkDiff, PositionalComparisonDisposition.DatatypeMismatch); - } - else if (Math.Abs(baselineDiff.SecondaryData.Length - checkDiff.SecondaryData.Length) > baselineDiff.LocationLeeway) - { - // The check data length is more than the allowed difference in length. - fileResult.AddPositionallyMatchedDifference(baselineDiff, checkDiff, PositionalComparisonDisposition.LengthMismatch); - } - else - { - fileResult.AddPositionallyMatchedDifference(baselineDiff, checkDiff, PositionalComparisonDisposition.Match); - } - - // The baseline & check differences are positionally similar in the above cases, both get consumed. - ++baselineDiffIndex; - ++checkDiffIndex; - } - } - - // One of the comparisons may have additional unhandled differences, can't possibly be both. - // So at most one of these loops can actually iterate. - while (baselineDiffIndex < BaselineComparisonDifferences.Differences.Count) - { - PositionalDifference baselineDiff = BaselineComparisonDifferences.Differences[baselineDiffIndex]; - fileResult.AddBaselineOnlyDifference(baselineDiff); - ++baselineDiffIndex; - } - - while (checkDiffIndex < CheckComparisonDifferences.Differences.Count) - { - PositionalDifference checkDiff = CheckComparisonDifferences.Differences[checkDiffIndex]; - fileResult.AddCheckOnlyDifference(checkDiff); - ++checkDiffIndex; - } - - // verify the results are sane - that all differences got classified. - int classifiedDiffCount = fileResult.BaselineOnlyDifferences.Count + fileResult.SecondaryOnlyDifferences.Count - + 2 * fileResult.PositionallyMatchedDifferences.Count; // these are counted twice because they consume both a baseline & secondary diff - int actualDiffCount = BaselineComparisonDifferences.Differences.Count + CheckComparisonDifferences.Differences.Count; - - if (classifiedDiffCount != actualDiffCount) - { - fileResult.HasDifferenceResolutionError = true; - } - - return fileResult; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/PositionalComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/PositionalComparisonDifference.cs deleted file mode 100644 index 4e16f2d6df5..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/PositionalComparisonDifference.cs +++ /dev/null @@ -1,27 +0,0 @@ -using BaselineComparer.TemplateComparison; - -namespace BaselineComparer.DifferenceComparison -{ - public enum PositionalComparisonDisposition - { - Match, - DatatypeMismatch, - LengthMismatch - }; - - public class PositionalComparisonDifference - { - public PositionalComparisonDifference(PositionalDifference baselineDifference, PositionalDifference checkDifference, PositionalComparisonDisposition disposition) - { - BaselineDifference = baselineDifference; - CheckDifference = checkDifference; - Disposition = disposition; - } - - public PositionalDifference BaselineDifference { get; } - - public PositionalDifference CheckDifference { get; } - - public PositionalComparisonDisposition Disposition { get; } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredDirectoryComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredDirectoryComparisonDifference.cs deleted file mode 100644 index b1f1d871019..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredDirectoryComparisonDifference.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; - -namespace BaselineComparer.DifferenceComparison -{ - public class StructuredDirectoryComparisonDifference - { - [JsonProperty] - public bool HasProblems - { - get - { - return FileResults.Any(x => x.HasDifferenceResolutionError || x.HasInvalidDifferences); - } - } - - [JsonProperty] - public bool InvalidBaselineData { get; set; } - - public bool ShouldSerializeInvalidBaselineData() - { - return InvalidBaselineData; - } - - [JsonProperty] - public bool InvalidSecondaryData { get; set; } - - public bool ShouldSerializeInvalidSecondaryData() - { - return InvalidSecondaryData; - } - - [JsonProperty] - public IReadOnlyList FileResults { get; set; } - - public static StructuredDirectoryComparisonDifference FromDirectoryComparisonDifference(DirectoryComparisonDifference difference) - { - StructuredDirectoryComparisonDifference structuredDifference = new StructuredDirectoryComparisonDifference() - { - InvalidBaselineData = difference.InvalidBaselineData, - InvalidSecondaryData = difference.InvalidSecondaryData, - FileResults = difference.FileResults.Select(x => StructuredFileComparisonDifference.FromFileComparisonDifference(x)).ToList() - }; - - return structuredDifference; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredFileComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredFileComparisonDifference.cs deleted file mode 100644 index 70e91696226..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredFileComparisonDifference.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using BaselineComparer.TemplateComparison; -using Newtonsoft.Json; - -namespace BaselineComparer.DifferenceComparison -{ - public class StructuredFileComparisonDifference - { - [JsonProperty] - public string Filename { get; set; } - - [JsonProperty] - public bool HasDifferenceResolutionError { get; set; } - - public bool ShouldSerializeHasDifferenceResolutionError() - { - return HasDifferenceResolutionError; - } - - [JsonProperty] - public bool HasInvalidDifferences { get; set; } - - public bool ShouldSerializeHasInvalidDifferences() - { - return HasInvalidDifferences; - } - - [JsonProperty] - public IReadOnlyList BaselineOnlyDifferences { get; set; } - - public bool ShouldSerializeBaselineOnlyDifferences() - { - return BaselineOnlyDifferences.Count > 0; - } - - [JsonProperty] - public IReadOnlyList SecondaryOnlyDifferences { get; set; } - - public bool ShouldSerializeSecondaryOnlyDifferences() - { - return SecondaryOnlyDifferences.Count > 0; - } - - [JsonProperty] - public IReadOnlyList FullyMatchedDifferences { get; set; } - - public bool ShouldSerializeFullyMatchedDifferences() - { - return FullyMatchedDifferences.Count > 0; - } - - [JsonProperty] - public IReadOnlyList PositionallyMatchedDifferencesWithIssues { get; set; } - - public bool ShouldSerializePositionallyMatchedDifferencesWithIssues() - { - return PositionallyMatchedDifferencesWithIssues.Count > 0; - } - - public bool MissingBaselineFile { get; set; } - - public bool ShouldSerializeMissingBaselineFile() - { - return MissingBaselineFile; - } - - public bool MissingSecondaryFile { get; set; } - - public bool ShouldSerializeMissingSecondaryFile() - { - return MissingSecondaryFile; - } - - public static StructuredFileComparisonDifference FromFileComparisonDifference(FileComparisonDifference differences) - { - StructuredFileComparisonDifference structuredDifference = new StructuredFileComparisonDifference() - { - Filename = differences.Filename, - HasDifferenceResolutionError = differences.HasDifferenceResolutionError, - HasInvalidDifferences = differences.AnyInvalidDifferences, - BaselineOnlyDifferences = differences.BaselineOnlyDifferences, - SecondaryOnlyDifferences = differences.SecondaryOnlyDifferences, - FullyMatchedDifferences = differences.PositionallyMatchedDifferences.Where(d => d.Disposition == PositionalComparisonDisposition.Match) - .Select(m => StructuredPositionalComparisonDifference.FromPositionalComparisonDifference(m)).ToList(), - PositionallyMatchedDifferencesWithIssues = differences.PositionallyMatchedDifferences.Where(d => d.Disposition != PositionalComparisonDisposition.Match) - .Select(m => StructuredPositionalComparisonDifference.FromPositionalComparisonDifference(m)).ToList(), - MissingBaselineFile = differences.MissingBaselineFile, - MissingSecondaryFile = differences.MissingSecondaryFile - }; - - return structuredDifference; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredPositionalComparisonDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredPositionalComparisonDifference.cs deleted file mode 100644 index d524a180886..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/DifferenceComparison/StructuredPositionalComparisonDifference.cs +++ /dev/null @@ -1,89 +0,0 @@ -using Newtonsoft.Json; - -namespace BaselineComparer.DifferenceComparison -{ - public class StructuredPositionalComparisonDifference - { - [JsonProperty] - public string MatchDisposition { get; set; } - - [JsonProperty] - public int BaselineMasterStartPosition { get; set; } - - [JsonProperty] - public string BaselineMasterData { get; set; } - - [JsonProperty] - public string BaselineClassification { get; set; } - - public bool ShouldSerializeBaselineClassification() - { - return !AreClassificationsTheSame; - } - - [JsonProperty] - public int BaselineSecondaryStartPosition { get; set; } - - [JsonProperty] - public string BaselineSecondaryData { get; set; } - - [JsonProperty] - public int ComparisonStartPosition { get; set; } - - [JsonProperty] - public string ComparisonData { get; set; } - - [JsonProperty] - public string ComparisonDataClassification { get; set; } - - public bool ShouldSerializeComparisonDataClassification() - { - return !AreClassificationsTheSame; - } - - [JsonProperty] - public string Classification - { - get - { - if (AreClassificationsTheSame) - { - return BaselineClassification; - } - - return null; - } - } - - public bool ShouldSerializeClassification() - { - return AreClassificationsTheSame; - } - - private bool AreClassificationsTheSame - { - get - { - return string.Equals(BaselineClassification, ComparisonDataClassification); - } - } - - public static StructuredPositionalComparisonDifference FromPositionalComparisonDifference(PositionalComparisonDifference difference) - { - StructuredPositionalComparisonDifference structuredDifference = new StructuredPositionalComparisonDifference() - { - MatchDisposition = difference.Disposition.ToString(), - BaselineMasterStartPosition = difference.BaselineDifference.BaselineStartPosition, - BaselineMasterData = difference.BaselineDifference.BaselineData, - BaselineClassification = difference.BaselineDifference.ClassificationString, - BaselineSecondaryStartPosition = difference.BaselineDifference.SecondaryStartPosition, - BaselineSecondaryData = difference.BaselineDifference.SecondaryData, - ComparisonStartPosition = difference.CheckDifference.SecondaryStartPosition, - ComparisonData = difference.CheckDifference.SecondaryData, - ComparisonDataClassification = difference.CheckDifference.ClassificationString - }; - - return structuredDifference; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/DirectoryCopy.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/DirectoryCopy.cs deleted file mode 100644 index 8e3651d1955..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/DirectoryCopy.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.IO; - -namespace BaselineComparer.Helpers -{ - public static class DirectoryCopy - { - public static void CopyDirectory(string sourceDirName, string destDirName, bool copySubDirs) - { - // Get the subdirectories for the specified directory. - DirectoryInfo dir = new DirectoryInfo(sourceDirName); - - if (!dir.Exists) - { - throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {sourceDirName}"); - } - - DirectoryInfo[] dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!Directory.Exists(destDirName)) - { - Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - FileInfo[] files = dir.GetFiles(); - foreach (FileInfo file in files) - { - string tempPath = Path.Combine(destDirName, file.Name); - file.CopyTo(tempPath, false); - } - - // If copying subdirectories, copy them and their contents to new location. - if (copySubDirs) - { - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - CopyDirectory(subdir.FullName, temppath, copySubDirs); - } - } - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/Proc.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/Proc.cs deleted file mode 100644 index 87a2d2a319d..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/Proc.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Diagnostics; - -namespace BaselineComparer.Helpers -{ - // copied from ProjectTestRunner - public class Proc - { - public static ProcessEx Run(string command, string args) - { - ProcessStartInfo psi = new ProcessStartInfo(command, args) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true - }; - Process p = Process.Start(psi); - ProcessEx wrapper = new ProcessEx(p); - return wrapper; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/ProcessEx.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/ProcessEx.cs deleted file mode 100644 index e93d69f48ae..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/ProcessEx.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Diagnostics; -using System.Text; - -namespace BaselineComparer.Helpers -{ - // copied from ProjectTestRunner - public class ProcessEx - { - private readonly Process _process; - private readonly StringBuilder _stderr; - private readonly StringBuilder _stdout; - - public ProcessEx(Process p) - { - _stdout = new StringBuilder(); - _stderr = new StringBuilder(); - - _process = p; - p.OutputDataReceived += OnOutputData; - p.ErrorDataReceived += OnErrorData; - p.BeginOutputReadLine(); - p.BeginErrorReadLine(); - } - - public string Error => _stderr.ToString(); - - public string Output => _stdout.ToString(); - - public int ExitCode => _process.ExitCode; - - public static implicit operator Process(ProcessEx self) - { - return self._process; - } - - private void OnErrorData(object sender, DataReceivedEventArgs e) - { - _stderr.AppendLine(e.Data); - try - { - Console.Error.WriteLine(e.Data); - } - catch - { - } - } - - private void OnOutputData(object sender, DataReceivedEventArgs e) - { - _stdout.AppendLine(e.Data); - - try - { - Console.WriteLine(e.Data); - } - catch - { - } - } - - public bool WaitForExit(int milliseconds) - { - return _process.WaitForExit(milliseconds); - } - - public void WaitForExit() - { - _process.WaitForExit(); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandReader.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandReader.cs deleted file mode 100644 index b93c0e16d33..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandReader.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace BaselineComparer.Helpers -{ - public static class TemplateCommandReader - { - public static IReadOnlyList ReadTemplateCommandFile(string filename) - { - List commandList = new List(); - - using (StreamReader commandReader = new StreamReader(filename)) - { - string line; - while ((line = commandReader.ReadLine()) != null) - { - if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) - { - continue; - } - - commandList.Add(line); - } - } - - return commandList; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandRunner.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandRunner.cs deleted file mode 100644 index 349bbd525ed..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateCommandRunner.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace BaselineComparer.Helpers -{ - public static class TemplateCommandRunner - { - public static bool RunTemplateCommand(string newCommand, string creationBaseDir, string templateCommand, string customHiveBasePath, bool isTemporaryHive) - { - List templateCommandList = new List() { templateCommand }; - - TemplateDataCreator dataCreator = new TemplateDataCreator(newCommand, creationBaseDir, templateCommandList, customHiveBasePath); - bool result = dataCreator.PerformTemplateCommands(isTemporaryHive); - - if (result) - { - Console.WriteLine("...data created successfully"); - } - else - { - Console.WriteLine("...Error creating data."); - } - - return result; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateDataCreator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateDataCreator.cs deleted file mode 100644 index 2a46405d6d0..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Helpers/TemplateDataCreator.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace BaselineComparer.Helpers -{ - public class TemplateDataCreator - { - public TemplateDataCreator(string dotnetCommand, string creationBaseDir, IReadOnlyList templateCommands, string customHiveBaseDir) - { - _dotnetCommand = dotnetCommand; - _creationBaseDir = creationBaseDir; - _templateCommands = templateCommands; - _customHiveBaseDir = customHiveBaseDir; - } - - public TemplateDataCreator(string dotnetCommand, string creationBaseDir, IReadOnlyList templateCommands) - { - _dotnetCommand = dotnetCommand; - _creationBaseDir = creationBaseDir; - _templateCommands = templateCommands; - _customHiveBaseDir = $"c:\\temp\\customHive-{Guid.NewGuid().ToString()}"; - } - - private readonly string _dotnetCommand; - private readonly string _creationBaseDir; - private readonly IReadOnlyList _templateCommands; - private readonly string _customHiveBaseDir; - - private bool ValidateProperties() - { - if (!string.Equals(_dotnetCommand, "new") && !string.Equals(_dotnetCommand, "new3")) - { - Console.WriteLine($"dotnet command arg value must be either 'new' or 'new3'. Actual = '{_dotnetCommand}"); - return false; - } - - if (Directory.Exists(_creationBaseDir)) - { - Console.WriteLine($"Template creation base directory '${_creationBaseDir}' already exists."); - return false; - } - else if (!Path.IsPathRooted(_creationBaseDir)) - { - Console.WriteLine($"Template creation base directory '${_creationBaseDir}' must be rooted"); - return false; - } - - return true; - } - - public bool PerformTemplateCommands(bool isTemporaryHive) - { - if (!ValidateProperties()) - { - return false; - } - - string originalDirectory = Directory.GetCurrentDirectory(); - if (!Directory.Exists(_creationBaseDir)) - { - Directory.CreateDirectory(_creationBaseDir); - } - Environment.CurrentDirectory = _creationBaseDir; - - if (isTemporaryHive) - { - InitializeHive(); - } - - foreach (string command in _templateCommands) - { - string args = $"{command} --debug:custom-hive {_customHiveBaseDir}"; - Run(args); - } - - Environment.CurrentDirectory = originalDirectory; - - if (isTemporaryHive) - { - RemoveHive(); - } - - return true; - } - - private void InitializeHive() - { - string args = $"--debug:reinit --debug:custom-hive {_customHiveBaseDir}"; - Console.WriteLine($"Reinitializing hive: {args}"); - Run(args); - } - - private void RemoveHive() - { - Directory.Delete(_customHiveBaseDir, true); - } - - private void Run(string args) - { - string commandArgs = _dotnetCommand + " " + args; - Console.WriteLine($"Running: dotnet {commandArgs}"); - - Proc.Run("dotnet", commandArgs).WaitForExit(); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationBaselineUnit.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationBaselineUnit.cs deleted file mode 100644 index d22028b702a..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationBaselineUnit.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - // part of the master baseline file - public class InvocationBaselineUnit - { - public InvocationBaselineUnit(string name, IReadOnlyList installRequirements, IReadOnlyList invocations) - { - Name = name; - InstallRequirements = installRequirements; - Invocations = invocations; - } - - [JsonProperty] - public string Name { get; } - - [JsonProperty] - public IReadOnlyList InstallRequirements { get; } - - public IReadOnlyList Invocations { get; } - - public static InvocationBaselineUnit FromJObject(JObject source) - { - string name = source.GetValue(nameof(Name)).ToString(); - - List installRequirementList = new List(); - JToken installToken = source.GetValue(nameof(InstallRequirements)); - foreach (string installItem in installToken.Values()) - { - installRequirementList.Add(installItem); - } - - List invocationData = new List(); - - foreach (JToken invocationJObject in source.GetValue(nameof(Invocations))) - { - invocationData.Add(BaselineCommandData.FromJObject((JObject)invocationJObject)); - } - - return new InvocationBaselineUnit(name, installRequirementList, invocationData); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationCommandData.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationCommandData.cs deleted file mode 100644 index af74aaa4f97..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationCommandData.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - // For reading a command file for initial baseline creation. - public class InvocationCommandData - { - public InvocationCommandData(IReadOnlyList invocations) - { - Invocations = invocations; - } - - public IReadOnlyList Invocations { get; } - - public static InvocationCommandData FromFile(string filename) - { - string fileContents; - - try - { - fileContents = File.ReadAllText(filename); - } - catch (Exception ex) - { - Console.WriteLine($"Unable to read the specified command file: {filename}"); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - - InvocationCommandData commandData; - - try - { - JObject source = JObject.Parse(fileContents); - commandData = FromJObject(source); - return commandData; - } - catch (Exception ex) - { - Console.WriteLine($"Unable to deserialize the invocation command file: {filename}"); - Console.WriteLine($"Error: {ex.Message}"); - throw; - } - } - - public static InvocationCommandData FromJObject(JObject source) - { - List invocationList = new List(); - JToken invocationListToken = source.GetValue(nameof(Invocations)); - - foreach (JObject invocationUnit in (JArray)invocationListToken) - { - InvocationUnit unit = InvocationUnit.FromJObject(invocationUnit); - invocationList.Add(unit); - } - - return new InvocationCommandData(invocationList); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationUnit.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationUnit.cs deleted file mode 100644 index db5c9e97c27..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/InvocationUnit.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer -{ - public class InvocationUnit - { - public InvocationUnit(string name, IReadOnlyList installRequirements, IReadOnlyList invocationCommands) - { - Name = name; - InstallRequirements = installRequirements; - InvocationCommands = invocationCommands; - } - - public string Name { get; } - public IReadOnlyList InstallRequirements { get; } - public IReadOnlyList InvocationCommands { get; } - - public static InvocationUnit FromJObject(JObject source) - { - string name = source.GetValue(nameof(Name)).ToString(); - - List installRequirements = new List(); - JToken installToken = source.GetValue(nameof(InstallRequirements)); - foreach (string toInstall in installToken.Values()) - { - installRequirements.Add(toInstall); - } - - List invocationCommands = new List(); - JToken invocationsToken = source.GetValue(nameof(InvocationCommands)); - foreach (string toInvoke in invocationsToken.Values()) - { - invocationCommands.Add(toInvoke); - } - - return new InvocationUnit(name, installRequirements, invocationCommands); - } - - public static InvocationUnit FromInvocationBaselineUnit(InvocationBaselineUnit baselinUnit) - { - return new InvocationUnit(baselinUnit.Name, baselinUnit.InstallRequirements, baselinUnit.Invocations.Select(x => x.Command).ToList()); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/Program.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/Program.cs deleted file mode 100644 index a11c8541fd3..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/Program.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using BaselineComparer.Helpers; - -namespace BaselineComparer -{ - class Program - { - static int Main(string[] args) - { - if (args.Length == 0) - { - ShowUsageMessage(); - return -1; - } - - if (string.Equals(args[0], "--create-baseline")) - { - if (args.Length != 4) - { - ShowUsageMessage(); - return -1; - } - - string dotnetCommand = args[1]; - string creationCommandFile = args[2]; - string outputBaseDir = args[3]; - - return CreateFileSeparatedBaseline(dotnetCommand, creationCommandFile, outputBaseDir); - } - - if (string.Equals(args[0], "--compare-to-baseline")) - { - if (args.Length != 3 && args.Length != 4) - { - ShowUsageMessage(); - return -1; - } - - string baselineBaseDir = args[1]; - string comparisonBaseDir = args[2]; - - bool debug = false; - if (args.Length == 4) - { - if (string.Equals(args[3], "--debug", StringComparison.Ordinal)) - { - debug = true; - Console.WriteLine("Attach & hit return."); - Console.ReadLine(); - } - else - { - ShowUsageMessage(); - return -1; - } - } - - return CreateFileSeparatedBaselineComparison(baselineBaseDir, comparisonBaseDir, debug); - } - - ShowUsageMessage(); - return -1; - } - - private static void ShowUsageMessage() - { - Console.WriteLine("Invalid args. Valid usage patterns:"); - Console.WriteLine("Generates 2 sets of templates using the creation commands, then compares them and writes a baseline report:"); - Console.WriteLine(" --create-baseline ."); - Console.WriteLine(); - - Console.WriteLine("Reads the baseline report, generates a set of templates using the commands in the baseline, compares to the baseline master data, then compares the comparison to the baseline comparison:"); - Console.WriteLine(" --compare-to-baseline ."); - Console.WriteLine(); - - Console.WriteLine("* Not directly part of baseline comparison. Generates a set of templates based on the command file:"); - Console.WriteLine(" --new-template-data "); - } - - public static int CreateFileSeparatedBaseline(string dotnetCommand, string creationCommandFile, string baselineBaseDir) - { - InvocationCommandData commandData = InvocationCommandData.FromFile(creationCommandFile); - BaselineCreator creator = new BaselineCreator(baselineBaseDir, dotnetCommand, commandData.Invocations); - creator.CreateBaseline(); - - return 0; - } - - public static int CreateFileSeparatedBaselineComparison(string baselineBaseDir, string comparisonBaseDir, bool debug) - { - // create the templates to compare to the baseline master data, and do the template-to-template comparisons. - TemplateCompareToBaselineReportCreator comparisonCreator = new TemplateCompareToBaselineReportCreator(baselineBaseDir, comparisonBaseDir); - comparisonCreator.CreateBaselineComparison(debug); - - // Compare the baseline comparisons against the newly created comparisons. - ComparisonComparisonReportCreator comparisonComparisonCreator = new ComparisonComparisonReportCreator(comparisonCreator.BaselineReportDir, comparisonCreator.ComparisonReportDir); - string comparisonComparisonReportDir = Path.Combine(comparisonBaseDir, "ComparisonComparisonReports"); - comparisonComparisonCreator.CreateComparisons(comparisonComparisonReportDir); - - return 0; - } - - // Runs the creation commands - // TODO: rework to use the same code wrapper as teh baseline and comparison creators... it's similar, but needs wrapping. - private static int NewTemplateData(string dotnetCommand, string creationCommandFile, string creationBaseDir) - { - IReadOnlyList templateCommands = TemplateCommandReader.ReadTemplateCommandFile(creationCommandFile); - - TemplateDataCreator dataCreator = new TemplateDataCreator(dotnetCommand, creationCommandFile, templateCommands); - bool result = dataCreator.PerformTemplateCommands(false); - - return result ? 0 : -1; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateCompareToBaselineReportCreator.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateCompareToBaselineReportCreator.cs deleted file mode 100644 index 73795402555..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateCompareToBaselineReportCreator.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using BaselineComparer.Helpers; - -namespace BaselineComparer -{ - // based on an existing baseline, creates one set of templates, and baseline-like reports for the new templates vs. the baseline master data. - public class TemplateCompareToBaselineReportCreator - { - private static readonly string ComparisonDataDirName = "Comparison"; - private static readonly string ComparisonReportDirName = "ComparisonReports"; - - // the setup of all the baseline related paths are assuming the baseline gets copied into the comparison root. - // This happens in CopyExistingBaseline() via CreateBaselineComparison() - public TemplateCompareToBaselineReportCreator(string baselineRoot, string comparisonRoot) - { - _baselineRoot = baselineRoot; - _comparisonRoot = comparisonRoot; - - string dataDir = Path.Combine(_comparisonRoot, BaselineCreator.BaseDataDir); - _masterDataBasePath = Path.Combine(dataDir, BaselineCreator.BaselineMasterDataDirName); - - _baselineReportDir = Path.Combine(_comparisonRoot, BaselineCreator.BaseReportDir); - - _comparisonDataDir = Path.Combine(dataDir, ComparisonDataDirName); - _comparisonReportDir = Path.Combine(_comparisonRoot, ComparisonReportDirName); - } - - private readonly string _baselineRoot; - private readonly string _comparisonRoot; - private readonly string _masterDataBasePath; - private readonly string _baselineReportDir; - - public string BaselineReportDir => _baselineReportDir; - - private readonly string _comparisonDataDir; - private readonly string _comparisonReportDir; - - public string ComparisonReportDir => _comparisonReportDir; - - private BaselineMasterReport _masterReport; - private IReadOnlyDictionary> _unitNameAndCommandToDataPathMap; - private IReadOnlyDictionary> _unitNameAndCommandToReportFileMap; - - public void CreateBaselineComparison(bool debugCompareOnly) - { - if (!debugCompareOnly) - { - CopyExistingBaseline(); - } - - ReadBaselineMasterReport(); - AssignRelativePathsAndReportNamesToCommandsFromMasterReport(); - - if (!debugCompareOnly) - { - if (!TryCreateTemplates()) - { - throw new Exception("There were problems creating the templates to compare."); - } - } - - IReadOnlyList invocationUnits = _masterReport.Invocations.Select(x => InvocationUnit.FromInvocationBaselineUnit(x)).ToList(); - BaselineReportCreator reportCreator = new BaselineReportCreator(_masterDataBasePath, _comparisonDataDir, invocationUnits, _unitNameAndCommandToDataPathMap, _unitNameAndCommandToReportFileMap); - reportCreator.WriteAllBaselineComparisons(_comparisonReportDir, _masterReport.NewCommand); - } - - private bool TryCreateTemplates() - { - bool allCreationsGood = true; - - foreach (InvocationBaselineUnit unit in _masterReport.Invocations) - { - CustomHiveCoordinator hive = new CustomHiveCoordinator(_masterReport.NewCommand, unit.InstallRequirements); - hive.InitializeHive(); - - IReadOnlyDictionary commandToPathMap = _unitNameAndCommandToDataPathMap[unit.Name]; - allCreationsGood &= hive.TryCreateTemplateData(_comparisonDataDir, commandToPathMap); - - hive.DeleteHive(); - } - - return allCreationsGood; - } - - private void ReadBaselineMasterReport() - { - string baselineMasterReportFilename = Path.Combine(_baselineReportDir, BaselineReportCreator.MasterBaselineReportFileName); - _masterReport = BaselineMasterReport.FromFile(baselineMasterReportFilename); - } - - private void AssignRelativePathsAndReportNamesToCommandsFromMasterReport() - { - Dictionary> unitCommandDataPaths = new Dictionary>(); - Dictionary> unitCommandReportFiles = new Dictionary>(); - - foreach (InvocationBaselineUnit unit in _masterReport.Invocations) - { - Dictionary commandPathsForUnit = new Dictionary(); - unitCommandDataPaths[unit.Name] = commandPathsForUnit; - Dictionary reportFilesForUnit = new Dictionary(); - unitCommandReportFiles[unit.Name] = reportFilesForUnit; - - foreach (BaselineCommandData commandData in unit.Invocations) - { - commandPathsForUnit[commandData.Command] = commandData.RelativePath; - reportFilesForUnit[commandData.Command] = commandData.ReportFileName; - } - } - - _unitNameAndCommandToDataPathMap = unitCommandDataPaths; - _unitNameAndCommandToReportFileMap = unitCommandReportFiles; - } - - private void CopyExistingBaseline() - { - Console.WriteLine("Copying baseline directory to comparison directory."); - DirectoryCopy.CopyDirectory(_baselineRoot, _comparisonRoot, true); - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryComparer.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryComparer.cs deleted file mode 100644 index 8983dcf0197..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryComparer.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace BaselineComparer.TemplateComparison -{ - public class DirectoryComparer - { - public DirectoryComparer(string baselineBaseDir, string secondaryBaseDir, string commonSubdir) - { - if (commonSubdir.EndsWith("\\")) - { - _baselineDataDir = Path.Combine(baselineBaseDir, commonSubdir); - _secondaryDataDir = Path.Combine(secondaryBaseDir, commonSubdir); - } - else - { - _baselineDataDir = Path.Combine(baselineBaseDir, commonSubdir) + "\\"; - _secondaryDataDir = Path.Combine(secondaryBaseDir, commonSubdir) + "\\"; - } - - _commonSubdir = commonSubdir; - } - - private readonly string _baselineDataDir; - private readonly string _secondaryDataDir; - private readonly string _commonSubdir; - - public DirectoryDifference Compare() - { - DirectoryDifference allResults = new DirectoryDifference(_commonSubdir); - - HashSet baselineFilenameLookup = new HashSet(); - List baselineOnly = new List(); - - foreach (string baselineFilename in Directory.EnumerateFiles(_baselineDataDir, "*.*", SearchOption.AllDirectories)) - { - string relativeFilename = baselineFilename.Substring(_baselineDataDir.Length); - baselineFilenameLookup.Add(relativeFilename); - string secondaryFilename = Path.Combine(_secondaryDataDir, relativeFilename); - - FileDifference fileDifference = new FileDifference(relativeFilename); - allResults.AddFileResult(fileDifference); - - if (!File.Exists(secondaryFilename)) - { - fileDifference.MissingSecondaryFile = true; - } - else - { - FileComparer fileComparer = new FileComparer(baselineFilename, secondaryFilename); - IReadOnlyList differenceList = fileComparer.Compare(); - - if (differenceList.Count > 0) - { - fileDifference.AddDifferences(differenceList); - } - } - } - - foreach (string secondaryFilename in Directory.EnumerateFiles(_secondaryDataDir, "*.*", SearchOption.AllDirectories)) - { - string relativeFilename = secondaryFilename.Substring(_secondaryDataDir.Length); - if (!baselineFilenameLookup.Contains(relativeFilename)) - { - string baselineFilename = Path.Combine(_baselineDataDir, relativeFilename); - FileDifference fileDifference = new FileDifference(relativeFilename); - fileDifference.MissingBaselineFile = true; - allResults.AddFileResult(fileDifference); - } - } - - return allResults; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryDifference.cs deleted file mode 100644 index dfae4ef68ac..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/DirectoryDifference.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer.TemplateComparison -{ - public class DirectoryDifference - { - public DirectoryDifference(string dataCommonSubdir) - { - DataCommonSubdir = dataCommonSubdir; - _fileResults = new List(); - } - - public void AddFileResult(FileDifference fileDiff) - { - _fileResults.Add(fileDiff); - } - - private List _fileResults; - - [JsonProperty] - public string DataCommonSubdir { get; set; } - - [JsonProperty] - public IReadOnlyList FileResults => _fileResults; - - [JsonIgnore] - public IReadOnlyList MissingBaselineFiles - { - get - { - return _fileResults.Where(file => file.MissingBaselineFile).Select(x => x.File).ToList(); - } - } - - [JsonIgnore] - public IReadOnlyList MissingSecondaryFiles - { - get - { - return _fileResults.Where(file => file.MissingSecondaryFile).Select(x => x.File).ToList(); - } - } - - // The comparison should only be valid for different runs of the same templates. - // The baseline isn't valid if: - // - There are any files in one directory but not the other. - // - Any of the files had differences deemed "too long" - public bool IsValidBaseline - { - get - { - if (MissingBaselineFiles.Count > 0) - { - return false; - } - - if (MissingSecondaryFiles.Count > 0) - { - return false; - } - - if (_fileResults.Any(file => file.Differences.Any(d => d.Classification == DifferenceDatatype.TooLong))) - { - return false; - } - - return true; - } - } - - public static DirectoryDifference FromJObject(JObject source) - { - string dataCommonSubdir = source.GetValue(nameof(DataCommonSubdir)).ToString(); - DirectoryDifference deserialized = new DirectoryDifference(dataCommonSubdir); - - foreach (JObject fileInfo in source.GetValue(nameof(FileResults))) - { - FileDifference fileDiff = FileDifference.FromJObject(fileInfo); - deserialized.AddFileResult(fileDiff); - } - - return deserialized; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileComparer.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileComparer.cs deleted file mode 100644 index c4e32a8cf09..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileComparer.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace BaselineComparer.TemplateComparison -{ - public class FileComparer - { - private static readonly int EndExtraDisplayLength = 128; // when one stream reaches the end, up to this many bytes of the other will be reported - private static readonly int DifferenceCheckWindowSize = 100; - private static readonly int PositionalSize = 10; - - private readonly string _baselineFilePath; - private readonly string _secondaryFilePath; - - private BufferedReadStream _baselineData; - private BufferedReadStream _secondaryData; - - public FileComparer(string baselineFilePath, string secondaryFilePath) - { - _baselineFilePath = baselineFilePath; - _secondaryFilePath = secondaryFilePath; - } - - public IReadOnlyList Compare() - { - List differenceList = new List(); - PositionalDifference endDifference; - bool unhandledDifference = false; - - using (FileStream baselineStream = File.Open(_baselineFilePath, FileMode.Open)) - using (FileStream secondaryStream = File.Open(_secondaryFilePath, FileMode.Open)) - { - _baselineData = new BufferedReadStream(baselineStream); - _secondaryData = new BufferedReadStream(secondaryStream); - - do - { - if (_baselineData.TryReadNext(out byte baselineByte) && _secondaryData.TryReadNext(out byte secondaryByte)) - { - if (baselineByte != secondaryByte) - { - if (TryFindDifferenceAtPosition(baselineByte, secondaryByte, out PositionalDifference difference)) - { - differenceList.Add(difference); - } - else - { - PositionalDifference tooLongDifference = SetupExplicitlyTypedDifference(DifferenceCheckWindowSize, DifferenceCheckWindowSize, baselineByte, secondaryByte, DifferenceDatatype.TooLong, 0); - differenceList.Add(tooLongDifference); - unhandledDifference = true; - } - } - } - } while (!IsDoneReading(out endDifference) && !unhandledDifference); - } - - if (endDifference != null) - { - differenceList.Add(endDifference); - } - - return differenceList; - } - - // naive, greedy determination of where a content difference ends. - private bool TryFindDifferenceAtPosition(byte previousBaselineByte, byte previousCheckByte, out PositionalDifference difference) - { - Dictionary> checkStartToBaselineStartMatches = FindPotentialRealignments(); - - if (checkStartToBaselineStartMatches.Count == 0) - { - difference = null; - return false; - } - - // the best difference is the one that has the smallest sum difference of start positions (sum of squares may yield a better result, may have to experiment) - int bestStartDelta = int.MaxValue; - int baselineStartOfBestRealign = int.MaxValue; - int checkStartOfBestRealign = int.MaxValue; - - foreach (KeyValuePair> candidate in checkStartToBaselineStartMatches) - { - int checkStartPosition = candidate.Key; - foreach (int baselineStartPosition in candidate.Value) - { - int startDelta = checkStartPosition + baselineStartPosition; - - if (startDelta < bestStartDelta) - { - bestStartDelta = startDelta; - baselineStartOfBestRealign = baselineStartPosition; - checkStartOfBestRealign = checkStartPosition; - } - else if ((startDelta == bestStartDelta) && (baselineStartOfBestRealign < baselineStartPosition)) - { - baselineStartOfBestRealign = baselineStartPosition; - checkStartOfBestRealign = checkStartPosition; - } - } - } - - if (bestStartDelta == int.MaxValue) - { // shouldn't be possible, but good to check while developing - difference = null; - return false; - } - - difference = SetupDifference(baselineStartOfBestRealign, checkStartOfBestRealign, previousBaselineByte, previousCheckByte); - - return true; - } - - private PositionalDifference SetupDifference(int baselineLength, int checkLength, byte baselineDiffFirstByte, byte checkDiffFirstByte) - { - int baselineDiffAbsoluteStart = _baselineData.LastReadPosition; - int checkDiffAbsoluteStart = _secondaryData.LastReadPosition; - byte[] baselineDiffPart = _baselineData.ReadBytes(baselineLength, out int baselineBytesActuallyRead); - byte[] checkDiffPart = _secondaryData.ReadBytes(checkLength, out int checkBytesActuallyRead); - - string baselineString = Convert.ToChar(baselineDiffFirstByte) + Encoding.Default.GetString(baselineDiffPart); - string checkString = Convert.ToChar(checkDiffFirstByte) + Encoding.Default.GetString(checkDiffPart); - return new PositionalDifference(baselineDiffAbsoluteStart, baselineString, checkDiffAbsoluteStart, checkString); - } - - private PositionalDifference SetupExplicitlyTypedDifference(int baselineLength, int checkLength, byte baselineDiffFirstByte, byte checkDiffFirstByte, DifferenceDatatype datatype, int leeway) - { - int baselineDiffAbsoluteStart = _baselineData.LastReadPosition; - int checkDiffAbsoluteStart = _secondaryData.LastReadPosition; - byte[] baselineDiffPart = _baselineData.ReadBytes(baselineLength, out int baselineBytesActuallyRead); - byte[] checkDiffPart = _secondaryData.ReadBytes(checkLength, out int checkBytesActuallyRead); - - string baselineString = Convert.ToChar(baselineDiffFirstByte) + Encoding.Default.GetString(baselineDiffPart); - string checkString = Convert.ToChar(checkDiffFirstByte) + Encoding.Default.GetString(checkDiffPart); - return new PositionalDifference(baselineDiffAbsoluteStart, baselineString, checkDiffAbsoluteStart, checkString, datatype, leeway); - } - - // Starting at the current position, looks for pairs of locations in the _baselineData & _secondaryData that are byte-wise equivalent. - // These are candidiates for where the difference ends. - private Dictionary> FindPotentialRealignments() - { - byte[] baselineReplayBuffer = _baselineData.ReadBytes(DifferenceCheckWindowSize, out int baselineBytesRead); - Span baselineSpan = baselineReplayBuffer; - - // setup the baseline lookups - Dictionary> baselinePositionals = new Dictionary>(StringComparer.Ordinal); - for (int start = 0; start < baselineBytesRead - PositionalSize; start++) - { - Span slice = baselineSpan.Slice(start, PositionalSize); - string sliceString = Encoding.Default.GetString(slice.ToArray()); - if (!baselinePositionals.TryGetValue(sliceString, out IList positions)) - { - positions = new List(); - baselinePositionals[sliceString] = positions; - } - - positions.Add(start); - } - - byte[] secondaryReplayBuffer = _secondaryData.ReadBytes(DifferenceCheckWindowSize, out int checkBytesRead); - Span secondarySpan = secondaryReplayBuffer; - - // start looking for "sames" in the check buffer - Dictionary> checkStartToBaselineStartMatches = new Dictionary>(); - int finalCheckSliceStart = Math.Min(baselineBytesRead, checkBytesRead) - PositionalSize; - - for (int start = 0; start < finalCheckSliceStart; start++) - { - Span slice = secondarySpan.Slice(start, PositionalSize); - string sliceString = Encoding.Default.GetString(slice.ToArray()); - if (baselinePositionals.TryGetValue(sliceString, out IList baselineMatchPositions)) - { - if (!checkStartToBaselineStartMatches.TryGetValue(start, out List baselineStartPositions)) - { - baselineStartPositions = new List(); - checkStartToBaselineStartMatches[start] = baselineStartPositions; - } - - baselineStartPositions.AddRange(baselineMatchPositions); - } - } - - _baselineData.SetupReplayBytes(baselineReplayBuffer); - _secondaryData.SetupReplayBytes(secondaryReplayBuffer); - - return checkStartToBaselineStartMatches; - } - - private bool IsDoneReading(out PositionalDifference endDifference) - { - if (_baselineData.DoneReading && _secondaryData.DoneReading) - { - endDifference = null; - return true; - } - else if (_baselineData.DoneReading) - { - string checkPartialEnd = ReadPartialEndData(_secondaryData); - endDifference = new PositionalDifference(_baselineData.LastReadPosition, string.Empty, _secondaryData.LastReadPosition, checkPartialEnd); - return true; - } - else if (_secondaryData.DoneReading) - { - string baselinePartialEnd = ReadPartialEndData(_baselineData); - endDifference = new PositionalDifference(_baselineData.LastReadPosition, baselinePartialEnd, _secondaryData.LastReadPosition, string.Empty); - return true; - } - - endDifference = null; - return false; - } - - private static string ReadPartialEndData(BufferedReadStream stream) - { - byte[] endPartialBuffer = new byte[EndExtraDisplayLength]; - int bytesRead = 0; - while (stream.TryReadNext(out byte nextByte) && bytesRead < EndExtraDisplayLength) - { - endPartialBuffer[bytesRead] = nextByte; - ++bytesRead; - } - - if (bytesRead == EndExtraDisplayLength) - { - return Convert.ToString(endPartialBuffer); - } - else - { - return Convert.ToString(endPartialBuffer) + "..."; - } - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileDifference.cs deleted file mode 100644 index eb60ea79be0..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/FileDifference.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer.TemplateComparison -{ - public class FileDifference - { - private List _differences; - private bool _missingBaselineFile; - private bool _missingCheckFile; - - public FileDifference(string file) - { - File = file; - _differences = new List(); - } - - [JsonProperty] - public string File { get; } - - public void AddDifference(PositionalDifference difference) - { - if (MissingBaselineFile || MissingSecondaryFile) - { - throw new Exception("Cant have differences if a file is missing."); - } - - _differences.Add(difference); - } - - public void AddDifferences(IEnumerable differeceList) - { - if (MissingBaselineFile || MissingSecondaryFile) - { - throw new Exception("Cant have differences if a file is missing."); - } - - _differences.AddRange(differeceList); - } - - [JsonProperty] - public IReadOnlyList Differences => _differences; - - public bool ShouldSerializeDifferences() - { - return Differences.Count > 0; - } - - [JsonProperty] - public bool MissingBaselineFile - { - get - { - return _missingBaselineFile; - } - set - { - if (_differences.Count > 0) - { - throw new Exception("Cant label file as missing - there are registered differences."); - } - - _missingBaselineFile = value; - } - } - - public bool ShouldSerializeMissingBaselineFile() - { - return MissingBaselineFile; - } - - [JsonProperty] - public bool MissingSecondaryFile - { - get - { - return _missingCheckFile; - } - set - { - if (_differences.Count > 0) - { - throw new Exception("Cant label file as missing - there are registered differences."); - } - - _missingCheckFile = value; - } - } - - public bool ShouldSerializeMissingSecondaryFile() - { - return MissingSecondaryFile; - } - - public static FileDifference FromJObject(JObject source) - { - string filename = source.GetValue(nameof(File)).ToString(); - - FileDifference fileDifference = new FileDifference(filename); - - if (source.TryGetValue(nameof(Differences), out JToken differenceJToken)) - { - foreach (JObject diffInfo in (JArray)differenceJToken) - { - PositionalDifference positionalDiff = PositionalDifference.FromJObject(diffInfo); - fileDifference.AddDifference(positionalDiff); - } - } - - return fileDifference; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/PositionalDifference.cs b/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/PositionalDifference.cs deleted file mode 100644 index 28c22754e95..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparer/TemplateComparison/PositionalDifference.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace BaselineComparer.TemplateComparison -{ - public enum DifferenceDatatype - { - Integer, - Decimal, - Guid, - String, // catchall for now - TooLong - }; - - public class PositionalDifference - { - public PositionalDifference(int baselineStart, string baselineData, int secondaryStart, string secondaryData, DifferenceDatatype classification, int leeway) - { - BaselineStartPosition = baselineStart; - BaselineData = baselineData; - SecondaryStartPosition = secondaryStart; - SecondaryData = secondaryData; - Classification = classification; - LocationLeeway = leeway; - } - - public PositionalDifference(int baselineStart, string baselineData, int secondaryStart, string secondaryData) - { - BaselineStartPosition = baselineStart; - BaselineData = baselineData; - SecondaryStartPosition = secondaryStart; - SecondaryData = secondaryData; - Classification = ClassifyDifference(out int leeway); - LocationLeeway = leeway; - } - - [JsonProperty] - public int BaselineStartPosition { get; } - - [JsonProperty] - public string BaselineData { get; } - - [JsonProperty] - public int SecondaryStartPosition { get; } - - [JsonProperty] - public string SecondaryData { get; } - - // Based on the classification of the difference, we may need to allow some leeway on the position of the difference for future comparisons. - // For example if in the baseline comparison, two generated ints are 65432 and 69999, the diff will start after the 6. - // But in future comparisons, we may be comparing 65432 and 12345, in which case the diff starts earlier. - // So if the diff is of the same classification and only varies by a "few" characters, it's probably ok. - [JsonProperty] - public int LocationLeeway { get; } - - [JsonIgnore] - public DifferenceDatatype Classification { get; } - - [JsonProperty] - public string ClassificationString => Classification.ToString(); - - // TODO (future enhancement): semantic version diff checking. Can use TemplateEngine.Utils.SemanticVersion.cs for parsing - // just need to be able to "walk around" the actual diff to get the full version string so it parses correctly. - // TODO (future enhancement): detect other "standard" data types. - private DifferenceDatatype ClassifyDifference(out int leeway) - { - if (IsIntegerDifference(out leeway)) - { - return DifferenceDatatype.Integer; - } - - if (IsDecimalDifference(out leeway)) - { - return DifferenceDatatype.Decimal; - } - - if (IsGuidDifference(out leeway)) - { - return DifferenceDatatype.Guid; - } - - leeway = 0; // not sure what's best here - return DifferenceDatatype.String; - } - - private bool IsDecimalDifference(out int leeway) - { - if (Double.TryParse(BaselineData, out double _) && Double.TryParse(SecondaryData, out double _)) - { - leeway = Math.Abs(BaselineData.Length - SecondaryData.Length) + 2; - return true; - } - - leeway = 0; - return false; - } - - private bool IsIntegerDifference(out int leeway) - { - if (Int32.TryParse(BaselineData, out int _) && Int32.TryParse(SecondaryData, out int _)) - { - leeway = Math.Abs(BaselineData.Length - SecondaryData.Length) + 2; - return true; - } - - leeway = 0; - return false; - } - - private bool IsGuidDifference(out int recommendedLeeway) - { - if (IsAlmostGuid(BaselineData, out int baselinePadding) && IsAlmostGuid(SecondaryData, out int secondaryPadding)) - { - recommendedLeeway = 4; // this would be the total number of characters at the start & end of the compared guids that are identical. More than 4 is very unlikely. - return true; - } - - recommendedLeeway = 0; - return false; - } - - // If 2 different guids have the same lead / trailing char(s) as each other, the diff checker won't pick up those characters because - // they aren't internal to the difference. - private bool IsAlmostGuid(string toCheck, out int paddingLength) - { - // allow for a few missing or extra chars, plus possible hyphens, plus possible braces or parens. - if (toCheck.Length > 38 || toCheck.Length < 28) - { - paddingLength = 0; - return false; - } - - if (toCheck[0] == '{' || toCheck[0] == '(') - { - toCheck = toCheck.Substring(1); - } - - int lastIndex = toCheck.Length - 1; - if (toCheck[lastIndex] == '}' || toCheck[lastIndex] == ')') - { - toCheck = toCheck.Substring(0, lastIndex); - } - - toCheck = toCheck.Replace("-", ""); - - if (toCheck.Length > 32) - { - paddingLength = 0; - return false; - } - - if (toCheck.Length < 32) - { - paddingLength = 32 - toCheck.Length; - toCheck = toCheck + new string('0', paddingLength); // pad to 32 chars - } - else - { - paddingLength = 0; - } - - return Guid.TryParse(toCheck, out Guid _); - } - - public void ConsoleDebug() - { - Console.WriteLine($"Baseline start: {BaselineStartPosition} | {BaselineData}"); - Console.WriteLine($"Target start: {SecondaryStartPosition} | {SecondaryData}"); - Console.WriteLine($"\tDatatype: {Classification.ToString()}"); - Console.WriteLine($"\tLeeway: {LocationLeeway}"); - } - - public static PositionalDifference FromJObject(JObject source) - { - int baselineStart = source.GetValue(nameof(BaselineStartPosition)).ToObject(); - string baselineData = source.GetValue(nameof(BaselineData)).ToString(); - int secondaryStart = source.GetValue(nameof(SecondaryStartPosition)).ToObject(); - string secondaryData = source.GetValue(nameof(SecondaryData)).ToString(); - - int leeway = source.GetValue(nameof(LocationLeeway)).ToObject(); - string classificationString = source.GetValue(nameof(ClassificationString)).ToString(); - DifferenceDatatype classification = Enum.Parse(classificationString); - - PositionalDifference difference = new PositionalDifference(baselineStart, baselineData, secondaryStart, secondaryData, classification, leeway); - - return difference; - } - } -} diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparerTests/BaselineComparerTests.csproj b/tools/legacy-tools/BaselineComparer/BaselineComparerTests/BaselineComparerTests.csproj deleted file mode 100644 index 239d3cd9cfb..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparerTests/BaselineComparerTests.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - Exe - $(NETCoreTargetFramework) - - - - - - - - - - - - diff --git a/tools/legacy-tools/BaselineComparer/BaselineComparerTests/FileDifferenceComparisonTests.cs b/tools/legacy-tools/BaselineComparer/BaselineComparerTests/FileDifferenceComparisonTests.cs deleted file mode 100644 index eb516b8d04f..00000000000 --- a/tools/legacy-tools/BaselineComparer/BaselineComparerTests/FileDifferenceComparisonTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -using BaselineComparer.DifferenceComparison; -using BaselineComparer.TemplateComparison; -using Newtonsoft.Json.Linq; -using Xunit; - -namespace BaselineComparerTests -{ - public class FileDifferenceComparisonTests - { - // Tests that "Close" but unaligned differences are all classified - that none of them get lost during attempted matching - [Fact(DisplayName = nameof(PartialDifferenceMialignmentTest))] - public void PartialDifferenceMialignmentTest() - { - string baselineDifference = @" - { - ""File"": ""Test_C\\Mvc_2.0_Ind_Uld_LS\\Properties\\launchSettings.json"", - ""Differences"": [ - { - ""BaselineStartPosition"": 165, - ""BaselineData"": ""31"", - ""SecondaryStartPosition"": 165, - ""SecondaryData"": ""64"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - }, - { - ""BaselineStartPosition"": 691, - ""BaselineData"": ""30"", - ""SecondaryStartPosition"": 691, - ""SecondaryData"": ""63"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - } - ] - } - "; - - string comparisonDifference = @" - { - ""File"": ""Test_C\\Mvc_2.0_Ind_Uld_LS\\Properties\\launchSettings.json"", - ""Differences"": [ - { - ""BaselineStartPosition"": 162, - ""BaselineData"": ""56131"", - ""SecondaryStartPosition"": 162, - ""SecondaryData"": ""22963"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - }, - { - ""BaselineStartPosition"": 192, - ""BaselineData"": ""84"", - ""SecondaryStartPosition"": 192, - ""SecondaryData"": ""33"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - }, - { - ""BaselineStartPosition"": 355, - ""BaselineData"": ""84"", - ""SecondaryStartPosition"": 355, - ""SecondaryData"": ""33"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - }, - { - ""BaselineStartPosition"": 688, - ""BaselineData"": ""56130"", - ""SecondaryStartPosition"": 688, - ""SecondaryData"": ""22962"", - ""LocationLeeway"": 2, - ""ClassificationString"": ""Integer"" - } - ] - } - "; - - JObject baselineJObject = JObject.Parse(baselineDifference); - JObject comparisonJObject = JObject.Parse(comparisonDifference); - - FileDifference baselineDiff = FileDifference.FromJObject(baselineJObject); - FileDifference comparisonDiff = FileDifference.FromJObject(comparisonJObject); - - FileDifferenceComparer comparer = new FileDifferenceComparer(baselineDiff, comparisonDiff); - FileComparisonDifference comparisonResult = comparer.Compare(); - - Assert.False(comparisonResult.HasDifferenceResolutionError); - } - } -} diff --git a/tools/legacy-tools/ComparisonCleanup/Program.cs b/tools/legacy-tools/ComparisonCleanup/Program.cs deleted file mode 100644 index fc1245149a6..00000000000 --- a/tools/legacy-tools/ComparisonCleanup/Program.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; - -namespace ComparisonCleanup -{ - class Program - { - private static readonly HashSet DirectoriesToRemove = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "bin", - "obj", - ".vs" - }; - - static void Main(string[] args) - { - if (args.Length == 0) - { - UsageMessage(); - return; - } - - string baseDir = args[0]; - if (!Directory.Exists(baseDir)) - { - Console.WriteLine($"directory '{baseDir}' doesn't exist"); - return; - } - - IList toRemove = new List(); - foreach (string directory in Directory.EnumerateDirectories(baseDir, "*", SearchOption.AllDirectories)) - { - string dirName = Path.GetFileName(directory); - - if (DirectoriesToRemove.Contains(dirName)) - { - toRemove.Add(directory); - Console.WriteLine($"going to delete: {directory}"); - } - } - - if (toRemove.Count == 0) - { - Console.WriteLine("Nothing found to delete...exiting"); - return; - } - - Console.WriteLine("Actually delete (Y/N)?"); - string confirmation = Console.ReadLine(); - if (!string.Equals(confirmation, "Y", StringComparison.OrdinalIgnoreCase)) - { - Console.WriteLine("Not deleting"); - return; - } - else - { - Console.WriteLine("Proceeding with deletes..."); - } - - foreach (string dirToRemove in toRemove) - { - Directory.Delete(dirToRemove, true); - } - } - - private static void UsageMessage() - { - Console.WriteLine("Usage: ComparisonCleanup "); - } - } -} diff --git a/tools/legacy-tools/DependencyUpdater/DependencyUpdater.csproj b/tools/legacy-tools/DependencyUpdater/DependencyUpdater.csproj deleted file mode 100644 index d5b1f4754bc..00000000000 --- a/tools/legacy-tools/DependencyUpdater/DependencyUpdater.csproj +++ /dev/null @@ -1,6 +0,0 @@ - - - $(NETCoreTargetFramework) - Exe - - \ No newline at end of file diff --git a/tools/legacy-tools/DependencyUpdater/EncodingUtil.cs b/tools/legacy-tools/DependencyUpdater/EncodingUtil.cs deleted file mode 100644 index c2604507635..00000000000 --- a/tools/legacy-tools/DependencyUpdater/EncodingUtil.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System.Text; - -namespace DependencyUpdater -{ - public class EncodingUtil - { - /// http://www.unicode.org/faq/utf_bom.html - public static Encoding Detect(byte[] buffer, int currentBufferLength, out byte[] bom) - { - if (currentBufferLength == 0) - { - //File is zero length - pick something - bom = new byte[0]; - return Encoding.UTF8; - } - - if (currentBufferLength >= 4) - { - if (buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) - { - //Big endian UTF-32 - bom = new byte[] { 0x00, 0x00, 0xFE, 0xFF }; - return Encoding.GetEncoding(12001); - } - - if (buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) - { - //Little endian UTF-32 - bom = new byte[] { 0xFF, 0xFE, 0x00, 0x00 }; - return Encoding.UTF32; - } - } - - if (currentBufferLength >= 3) - { - if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) - { - //UTF-8 - bom = new byte[] { 0xEF, 0xBB, 0xBF }; - return Encoding.UTF8; - } - } - - if (currentBufferLength >= 2) - { - if (buffer[0] == 0xFE && buffer[1] == 0xFF) - { - //Big endian UTF-16 - bom = new byte[] { 0xFE, 0xFF }; - return Encoding.BigEndianUnicode; - } - - if (buffer[0] == 0xFF && buffer[1] == 0xFE) - { - //Little endian UTF-16 - bom = new byte[] { 0xFF, 0xFE }; - return Encoding.Unicode; - } - } - - //Fallback to UTF-8 - bom = new byte[0]; - return Encoding.UTF8; - } - } -} diff --git a/tools/legacy-tools/DependencyUpdater/Program.cs b/tools/legacy-tools/DependencyUpdater/Program.cs deleted file mode 100644 index 2c47629f73c..00000000000 --- a/tools/legacy-tools/DependencyUpdater/Program.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; - -namespace DependencyUpdater -{ - class Program - { - static int Main(string[] args) - { - if(args.Length < 2) - { - Console.WriteLine(@"Usage: -dotnet DependencyUpdater.dll [path to templates:string] [infer no-timestamp packages from semaphore files] [[paths to package sources]]"); - return -1; - } - - bool NoTimestamp = bool.Parse(args[1]); - string root = args[0]; - List sources = new List(); - - foreach(string arg in args.Skip(2)) - { - if (Directory.Exists(arg)) - { - sources.Add(arg); - } - else if (File.Exists(arg)) - { - string sem = File.ReadAllText(arg); - - foreach (string line in sem.Split('\n')) - { - string trimmed = line.Trim(); - string share = trimmed.Substring(trimmed.LastIndexOf(':') + 1).Trim(); - string source = Path.Combine(share, @"Signed\Packages") + (NoTimestamp ? "-NoTimeStamp" : ""); - - if (Directory.Exists(source)) - { - sources.Add(source); - } - } - } - else - { - Console.Error.WriteLine($"Unknown source: \"{arg}\""); - } - } - - Regex versionPattern = new Regex(@"\d+\.\d+\.\d+([-\+].*)?"); - List> replacements = new List>(); - - foreach (string source in sources) - { - foreach (string file in Directory.EnumerateFiles(source, "*.nupkg", SearchOption.AllDirectories)) - { - string packageIdAndVersion = Path.GetFileNameWithoutExtension(file); - Match m = versionPattern.Match(packageIdAndVersion); - string packageId = packageIdAndVersion.Substring(0, m.Index).TrimEnd('.'); - string version = packageIdAndVersion.Substring(m.Index); - int versionFirstDot = version.IndexOf('.'); - int versionSecondDot = version.IndexOf('.', versionFirstDot + 1); - string majorMinor = version.Substring(0, versionSecondDot); - string majorMinorEscaped = Regex.Escape(majorMinor); - - Regex rx = new Regex($"(?<=\"{packageId}\"\\s+Version\\s*=\\s*\"){majorMinorEscaped}[^\"]*(?=\")"); - replacements.Add(Tuple.Create(packageId, rx, version)); - } - } - - foreach(string project in Directory.EnumerateFiles(root, "*.*proj", SearchOption.AllDirectories)) - { - if(Path.GetExtension(project).ToUpperInvariant() == ".PROJ" || Path.GetFileName(project).ToUpperInvariant() == "BUILD.CSPROJ") - { - continue; - } - - string source = File.ReadAllText(project); - string result = source; - foreach(Tuple replacement in replacements) - { - string orig = result; - result = replacement.Item2.Replace(result, replacement.Item3); - - if(orig != result) - { - Console.WriteLine($"{project.Substring(root.Length).TrimStart('\\', '/')}: {replacement.Item1} -> {replacement.Item3}"); - } - } - - byte[] data = File.ReadAllBytes(project); - Encoding encoding = EncodingUtil.Detect(data, data.Length, out byte[] bom); - - if(bom.Length == 0 && Encoding.UTF8.EncodingName == encoding.EncodingName) - { - encoding = new UTF8Encoding(false); - } - - File.WriteAllText(project, result, encoding); - } - - return 0; - } - } -} diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ComparisonConfig.cs b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ComparisonConfig.cs deleted file mode 100644 index a7a9d5df57e..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ComparisonConfig.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Microsoft.TemplateSearch.ScraperOutputComparison -{ - internal class ComparisonConfig - { - public ComparisonConfig(string scraperOutputOneFile, string scraperOutputTwoFile, string comparisonResultFile) - { - ScraperOutputOneFile = scraperOutputOneFile; - ScraperOutputTwoFile = scraperOutputTwoFile; - ComparisonResultFile = comparisonResultFile; - } - - public string ScraperOutputOneFile { get; } - - public string ScraperOutputTwoFile { get; } - - public string ComparisonResultFile { get; } - } -} diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Microsoft.TemplateSearch.ScraperOutputComparison.csproj b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Microsoft.TemplateSearch.ScraperOutputComparison.csproj deleted file mode 100644 index 0dc2fc12435..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Microsoft.TemplateSearch.ScraperOutputComparison.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - Exe - $(NETCoreTargetFramework) - enable - - - - - - - - - - - - - diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Program.cs b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Program.cs deleted file mode 100644 index ec56ee0de3b..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/Program.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Newtonsoft.Json.Linq; - -namespace Microsoft.TemplateSearch.ScraperOutputComparison -{ - internal class Program - { - private static void Main(string[] args) - { - if (!TryParseArgs(args, out ComparisonConfig comparisonConfig)) - { - DisplayUsage(); - return; - } - - using ScrapeComparer comparer = new ScrapeComparer(comparisonConfig); - if (!comparer.Compare(out ScrapeComparisonResult comparisonResult)) - { - Console.WriteLine("Unable to read one or both of the scraper outputs to compare"); - return; - } - - if (TryWriteComparisonResults(comparisonConfig, comparisonResult)) - { - Console.WriteLine("Successfully wrote the comparison result file"); - } - else - { - Console.WriteLine("Error writing the comparison file"); - } - } - - private static bool TryWriteComparisonResults(ComparisonConfig config, ScrapeComparisonResult comparisonResult) - { - try - { - JObject toSerialize = JObject.FromObject(comparisonResult); - - string outputDirectory = Path.GetDirectoryName(config.ComparisonResultFile); - if (!Directory.Exists(outputDirectory)) - { - Directory.CreateDirectory(outputDirectory); - } - - File.WriteAllText(config.ComparisonResultFile, toSerialize.ToString()); - return true; - } - catch - { - return false; - } - } - - private static bool TryParseArgs(string[] args, out ComparisonConfig comparisonConfig) - { - if (args.Length != 3) - { - comparisonConfig = null; - return false; - } - - string scraperOutputOnePath = args[0]; - string scraperOutputTwoPath = args[1]; - string comparisonResultFile = args[2]; - - if (!File.Exists(scraperOutputOnePath)) - { - Console.WriteLine($"Scraper output file '{scraperOutputOnePath}' does not exist"); - comparisonConfig = null; - return false; - } - - if (!File.Exists(scraperOutputTwoPath)) - { - Console.WriteLine($"Scraper output file '{scraperOutputTwoPath}' does not exist"); - comparisonConfig = null; - return false; - } - - if (File.Exists(comparisonResultFile)) - { - Console.WriteLine($"Comparison result file '{comparisonResultFile}' already exists. Exiting to avoid overwriting it."); - comparisonConfig = null; - return false; - } - - comparisonConfig = new ComparisonConfig(scraperOutputOnePath, scraperOutputTwoPath, comparisonResultFile); - return true; - } - - private static void DisplayUsage() - { - Console.WriteLine("Usage:"); - Console.WriteLine("Running the comparer requires 3 args. The first two are the paths to the scraper files to compare. The third is the output file for the comparison results."); - } - } -} diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparer.cs b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparer.cs deleted file mode 100644 index a4d0f0a312d..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparer.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Microsoft.TemplateEngine.Abstractions; -using Microsoft.TemplateEngine.Edge; -using Microsoft.TemplateSearch.Common; - -namespace Microsoft.TemplateSearch.ScraperOutputComparison -{ - internal class ScrapeComparer : IDisposable - { - private readonly ComparisonConfig _config; - - private readonly EngineEnvironmentSettings _environmentSettings; - - public ScrapeComparer(ComparisonConfig config) - { - _config = config; - ITemplateEngineHost host = TemplateEngineHostHelper.CreateHost("Comparison"); - _environmentSettings = new EngineEnvironmentSettings(host, virtualizeSettings: true); - } - - // For now, it's just going to check the packs between the two runs - // As desired, add more comparisons, and expand the definition of ScrapeComparisonResult - public bool Compare(out ScrapeComparisonResult result) - { -#pragma warning disable CS0618 // Type or member is obsolete - if (!TryReadScraperOutput(_config.ScraperOutputOneFile, out TemplateDiscoveryMetadata scraperOutputOne) - || !TryReadScraperOutput(_config.ScraperOutputTwoFile, out TemplateDiscoveryMetadata scraperOutputTwo)) -#pragma warning restore CS0618 // Type or member is obsolete - { - result = null; - return false; - } - - // In one but not two - HashSet scraperOnePacks = new HashSet(scraperOutputOne.PackToTemplateMap.Keys); - scraperOnePacks.ExceptWith(scraperOutputTwo.PackToTemplateMap.Keys); - - // In two but not one - HashSet scraperTwoPacks = new HashSet(scraperOutputTwo.PackToTemplateMap.Keys); - scraperTwoPacks.ExceptWith(scraperOutputOne.PackToTemplateMap.Keys); - - result = new ScrapeComparisonResult(_config.ScraperOutputOneFile, _config.ScraperOutputTwoFile, scraperOnePacks.ToList(), scraperTwoPacks.ToList()); - return true; - } - - public void Dispose() - { - _environmentSettings.Dispose(); - } - -#pragma warning disable CS0618, CS0612 // Type or member is obsolete - private bool TryReadScraperOutput(string scrapeFilePath, out TemplateDiscoveryMetadata discoveryMetadata) - { - return LegacySearchCacheReader.TryReadDiscoveryMetadata(_environmentSettings, scrapeFilePath, null, out discoveryMetadata); - } -#pragma warning restore CS0618, CS0612 // Type or member is obsolete - } -} diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparisonResult.cs b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparisonResult.cs deleted file mode 100644 index 6ae8a660bb8..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/ScrapeComparisonResult.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace Microsoft.TemplateSearch.ScraperOutputComparison -{ - internal class ScrapeComparisonResult - { - public ScrapeComparisonResult(string firstScrapeFile, string secondScrapeFile, List packsInFirstScrapeOnly, List packsInSecondScrapeOnly) - { - FirstScrapeFile = firstScrapeFile; - SecondScrapeFile = secondScrapeFile; - PacksInFirstScrapeOnly = packsInFirstScrapeOnly; - PacksInSecondScrapeOnly = packsInSecondScrapeOnly; - } - - public string FirstScrapeFile { get; } - - public string SecondScrapeFile { get; } - - public List PacksInFirstScrapeOnly { get; } - - public List PacksInSecondScrapeOnly { get; } - } -} diff --git a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/TemplateEngineHostHelper.cs b/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/TemplateEngineHostHelper.cs deleted file mode 100644 index 4a61962ea14..00000000000 --- a/tools/legacy-tools/Microsoft.TemplateSearch.ScraperOutputComparison/TemplateEngineHostHelper.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#nullable enable - -using Microsoft.TemplateEngine.Edge; - -namespace Microsoft.TemplateSearch.ScraperOutputComparison -{ - public static class TemplateEngineHostHelper - { - private const string DefaultHostVersion = "1.0.0"; - - private static readonly Dictionary DefaultPreferences = new Dictionary - { - { "prefs:language", "C#" } - }; - - public static DefaultTemplateEngineHost CreateHost(string hostIdentifier) - { - if (string.IsNullOrEmpty(hostIdentifier)) - { - throw new ArgumentException("hostIdentifier cannot be null"); - } - // use "dotnetcli" as a fallback host so the correct host specific files are read. - DefaultTemplateEngineHost host = new DefaultTemplateEngineHost(hostIdentifier, DefaultHostVersion, DefaultPreferences, null, new[] { "dotnetcli" }); - return host; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Battery.cs b/tools/legacy-tools/ProjectTestRunner/Battery.cs deleted file mode 100644 index df1ef7b7518..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Battery.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; -using ProjectTestRunner.Handlers; -using ProjectTestRunner.Helpers; -using Xunit; -using Xunit.Abstractions; - -[assembly: CollectionBehavior(DisableTestParallelization = true)] - -namespace ProjectTestRunner -{ - public class Battery - { - private static readonly IReadOnlyDictionary HandlerLookup = new Dictionary - { - { ExecuteHandler.Handler, new ExecuteHandler() }, - { TaskKillHandler.Handler, new TaskKillHandler() }, - { HttpRequestHandler.Handler, new HttpRequestHandler() }, - { FindProcessHandler.Handler, new FindProcessHandler() }, - { FileInspectHandler.Handler, new FileInspectHandler() }, - { DirectoryInspectHandler.Handler, new DirectoryInspectHandler() }, - }; - - private static readonly string Creator; - private static readonly string BasePath; - - static Battery() - { - string assemblyPath = typeof(Battery).GetTypeInfo().Assembly.CodeBase; - Uri assemblyUri = new Uri(assemblyPath, UriKind.Absolute); - assemblyPath = assemblyUri.LocalPath; - BasePath = Path.GetDirectoryName(assemblyPath); - - Creator = Environment.GetEnvironmentVariable("CREATION_TEST_RUNNER"); - - if (string.IsNullOrWhiteSpace(Creator)) - { - Creator = "new"; - } - - Proc.Run("dotnet", $"{Creator} --debug:reinit").WaitForExit(); - Proc.Run("dotnet", $"{Creator}").WaitForExit(); - - string templateFeedDirectory = FindTemplateFeedDirectory(BasePath); - Proc.Run("dotnet", $"{Creator} -i \"{templateFeedDirectory}\"").WaitForExit(); - } - - public Battery(ITestOutputHelper outputHelper) - { - Console.SetOut(new OutputHelperHelper(outputHelper)); - Console.SetError(new OutputHelperHelper(outputHelper)); - } - - [PrettyTheory, MemberData(nameof(Discover))] - public void Run(params string[] file) - { - string[] allParts = new string[file.Length + 2]; - allParts[0] = BasePath; - allParts[1] = "TestCases"; - - for (int i = 0; i < file.Length; ++i) - { - allParts[i + 2] = file[i]; - } - - string contents = File.ReadAllText(Path.Combine(allParts)); - contents = Environment.ExpandEnvironmentVariables(contents); - - JObject json = JObject.Parse(contents); - - if (json["skip"]?.Value() ?? false) - { - Console.WriteLine("Test Skipped"); - return; - } - - string targetPath = Path.Combine(Path.GetTempPath(), "_" + Guid.NewGuid().ToString().Replace("-", "")); - try - { - string install = json["install"]?.ToString(); - string command = json["create"].ToString(); - Console.WriteLine("Testing: " + json["name"].ToString()); - Dictionary dict = new Dictionary - { - { "targetPath", targetPath}, - { "targetPathName", Path.GetFileName(targetPath)}, - }; - - List results = new List(); - IHandlerResult current; - string message; - - if (!string.IsNullOrWhiteSpace(install)) - { - Console.WriteLine($"Executing step {(results.Count + 1)} (install)..."); - current = Install(Creator, install); - - message = current.VerificationSuccess ? $"PASS ({current.Duration})" : $"FAIL ({current.Duration}): {current.FailureMessage}"; - Console.WriteLine($" {message}"); - Console.WriteLine(" "); - - if (!current.VerificationSuccess) - { - Assert.False(true, current.FailureMessage); - } - } - - Console.WriteLine($"Executing step {(results.Count + 1)} (create)..."); - current = Create(Creator, install, command, targetPath); - - message = current.VerificationSuccess ? $"PASS ({current.Duration})" : $"FAIL ({current.Duration}): {current.FailureMessage}"; - Console.WriteLine($" {message}"); - Console.WriteLine(" "); - - if (!current.VerificationSuccess) - { - Assert.False(true, current.FailureMessage); - } - - results.Add(current); - - foreach (JObject entry in ((JArray)json["tasks"]).Children().OfType()) - { - string handlerKey = entry["handler"].ToString(); - IHandler handler = HandlerLookup[handlerKey]; - Console.WriteLine($"Executing step {(results.Count + 1)} ({handler.Summarize(dict, entry)})..."); - current = handler.Execute(dict, results, entry); - message = current.VerificationSuccess ? $"PASS ({current.Duration})" : $"FAIL ({current.Duration}): {current.FailureMessage}"; - Console.WriteLine($" {message}"); - Console.WriteLine(" "); - results.Add(current); - } - - foreach (IHandlerResult result in results) - { - Assert.False(!result.VerificationSuccess, result.FailureMessage); - } - } - finally - { - for (int i = 0; i < 5; ++i) - { - try - { - Directory.Delete(targetPath, true); - break; - } - catch - { - Thread.Sleep(500); - } - } - } - } - - private IHandlerResult Install(string creator, string installPackage) - { - Stopwatch watch = Stopwatch.StartNew(); - try - { - Process install = Proc.Run("dotnet", $"{creator} -i \"{installPackage}\""); - install.WaitForExit(); - - if (install.ExitCode != 0) - { - return new GenericHandlerResult(watch.Elapsed, false, $"\"{installPackage}\" failed to install"); - } - - return new GenericHandlerResult(watch.Elapsed, true, null); - } - finally - { - watch.Stop(); - } - } - - private static string FindTemplateFeedDirectory(string batteryDirectory) - { - DirectoryInfo currentDirectory = new DirectoryInfo(batteryDirectory); - string templateFeed = Path.Combine(currentDirectory.FullName, "template_feed"); - - while (!Directory.Exists(templateFeed)) - { - currentDirectory = currentDirectory.Parent; - templateFeed = Path.Combine(currentDirectory.FullName, "template_feed"); - } - - return templateFeed; - } - - private static IHandlerResult Create(string creator, string installPackage, string command, string targetPath) - { - Stopwatch watch = Stopwatch.StartNew(); - try - { - Directory.CreateDirectory(targetPath); - Process create = Proc.Run("dotnet", $"{creator} {command} -o \"{targetPath}\""); - create.WaitForExit(); - - if (create.ExitCode != 0) - { - return new GenericHandlerResult(watch.Elapsed, false, $"\"{command}\" failed create"); - } - - Directory.SetCurrentDirectory(targetPath); - return new GenericHandlerResult(watch.Elapsed, true, null); - } - finally - { - watch.Stop(); - } - } - - public static IEnumerable Discover() - { - string basePath = Path.Combine(BasePath, "TestCases"); - - foreach (string testCase in Directory.EnumerateFiles(basePath, "*.json", SearchOption.AllDirectories)) - { - string relPath = testCase.Substring(basePath.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - string[] file = relPath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - yield return file; - } - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/HandlerResults/ExecuteHandlerResult.cs b/tools/legacy-tools/ProjectTestRunner/HandlerResults/ExecuteHandlerResult.cs deleted file mode 100644 index d90a007af4e..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/HandlerResults/ExecuteHandlerResult.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Diagnostics; - -namespace ProjectTestRunner.HandlerResults -{ - internal class ExecuteHandlerResult : IHandlerResult - { - private readonly Process _process; - - public ExecuteHandlerResult(TimeSpan duration, bool verificationSuccess, string failureMessage, Process process = null, string name = null) - { - Duration = duration; - _process = process; - Name = name; - VerificationSuccess = verificationSuccess; - FailureMessage = failureMessage; - } - - public bool VerificationSuccess { get; } - - public string FailureMessage { get; } - - public string Name { get; } - - public TimeSpan Duration { get; } - - public void Kill() - { - _process?.Kill(); - } - } -} \ No newline at end of file diff --git a/tools/legacy-tools/ProjectTestRunner/HandlerResults/GenericHandlerResult.cs b/tools/legacy-tools/ProjectTestRunner/HandlerResults/GenericHandlerResult.cs deleted file mode 100644 index edfe0796389..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/HandlerResults/GenericHandlerResult.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace ProjectTestRunner.HandlerResults -{ - internal class GenericHandlerResult : IHandlerResult - { - public GenericHandlerResult(TimeSpan duration, bool verificationSuccess, string failureMessage, string name = null) - { - Duration = duration; - Name = name; - VerificationSuccess = verificationSuccess; - FailureMessage = failureMessage; - } - - public string Name { get; } - - public bool VerificationSuccess { get; } - - public string FailureMessage { get; } - - public TimeSpan Duration { get; } - } -} \ No newline at end of file diff --git a/tools/legacy-tools/ProjectTestRunner/HandlerResults/IHandlerResult.cs b/tools/legacy-tools/ProjectTestRunner/HandlerResults/IHandlerResult.cs deleted file mode 100644 index 17587f09d41..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/HandlerResults/IHandlerResult.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace ProjectTestRunner.HandlerResults -{ - public interface IHandlerResult - { - string Name { get; } - - bool VerificationSuccess { get; } - - string FailureMessage { get; } - - TimeSpan Duration { get; } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/DirectoryInspectHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/DirectoryInspectHandler.cs deleted file mode 100644 index f12449d815f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/DirectoryInspectHandler.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - // - // directory: rel path to directory - // assertion: exists | does_not_exist - - public class DirectoryInspectHandler : IHandler - { - public static string Handler => "directoryInspect"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - try - { - string basePath = tokens["targetPath"]; - - string name = json["name"]?.ToString(); - string directoryName = json["directory"].ToString(); - string pathToDirectory = Path.Combine(basePath, directoryName); - string assertion = json["assertion"].ToString(); - bool doesDirectoryExist = Directory.Exists(pathToDirectory); - - if (string.Equals(assertion, "exists", StringComparison.OrdinalIgnoreCase)) - { - if (!doesDirectoryExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected directory {directoryName} to exist, but it did not", name: name); - } - } - else if (string.Equals(assertion, "does_not_exist", StringComparison.OrdinalIgnoreCase)) - { - if (doesDirectoryExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected directory {directoryName} to not exist, but it did", name: name); - } - } - - return new GenericHandlerResult(watch.Elapsed, true, null); - } - catch (Exception ex) - { - return new GenericHandlerResult(watch.Elapsed, false, ex.Message); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - string directoryName = json["directory"].ToString(); - string assertion = json["assertion"].ToString().ToLowerInvariant().Replace("_", " "); - - return $"Directory inspection - checking if directory \"{directoryName}\" {assertion}"; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/ExecuteHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/ExecuteHandler.cs deleted file mode 100644 index 9679c33cae1..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/ExecuteHandler.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; -using ProjectTestRunner.Helpers; - -namespace ProjectTestRunner.Handlers -{ - public class ExecuteHandler : IHandler - { - public static string Handler => "execute"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - try - { - string args = json["args"].ToString(); - - foreach (KeyValuePair entry in tokens) - { - args = args.Replace($"%{entry.Key}%", entry.Value); - } - - string command = json["command"].ToString(); - ProcessEx p = Proc.Run(command, args); - string name = json["name"]?.ToString(); - - if (json["noExit"]?.Value() ?? false) - { - if (p.WaitForExit(json["exitTimeout"]?.Value() ?? 1000)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, "Process exited unexpectedly", name: name); - } - - return new ExecuteHandlerResult(watch.Elapsed, true, null, p, name); - } - else - { - p.WaitForExit(); - int expectedExitCode = json["exitCode"]?.Value() ?? 0; - bool success = expectedExitCode == p.ExitCode; - - if (!success) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Process exited with code {p.ExitCode} instead of {expectedExitCode}", name: name); - } - - JArray expectations = json["expectations"]?.Value(); - - if(expectations != null) - { - foreach(JObject expectation in expectations.Children().OfType()) - { - string assertion = expectation["assertion"]?.Value()?.ToUpperInvariant(); - string s; - StringComparison c; - - switch (assertion) - { - case "OUTPUT_CONTAINS": - s = expectation["text"]?.Value(); - if(!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if(p.Output.IndexOf(s, c) < 0) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected output to contain \"{s}\" ({c}), but it did not", name: name); - } - - break; - case "OUTPUT_DOES_NOT_CONTAIN": - s = expectation["text"]?.Value(); - if (!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if (p.Output.IndexOf(s, c) > -1) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected output to NOT contain \"{s}\" ({c}), but it did", name: name); - } - - break; - default: - return new ExecuteHandlerResult(watch.Elapsed, false, $"Unkown assertion: {assertion}", name: name); - } - } - } - - return new ExecuteHandlerResult(watch.Elapsed, true, null, name: name); - } - } - finally - { - watch.Stop(); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - string args = json["args"].ToString(); - - foreach (KeyValuePair entry in tokens) - { - args = args.Replace($"%{entry.Key}%", entry.Value); - } - - string command = json["command"].ToString(); - - return $"Execute {command} {args}"; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/FileInspectHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/FileInspectHandler.cs deleted file mode 100644 index b26dd6ef0cb..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/FileInspectHandler.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - // file: rel path to file - // Note: For filenames that get modified by the template creation name, use the literal "%targetPathName%". - // It gets replaced with the creation name. - // Example: "filename": "%targetPathName%.csproj" - // expectations: - // assertion: exists | does_not_exist | contains | does_not_contain - // text: text to check for when using (file_contains | file_does_not_contain) - // comparison: a StringComparison enum value - - // Example: - // { - // "handler": "fileInspect", - // "file": "filename" - // "expectations": [ - // { - // "assertion": "exists" - // }, - // { - // "assertion": "contains", - // "text": "netcoreapp1.0", - // "comparison": "Ordinal", - // }, - // { - // "assertion": "does_not_contain", - // "text": "TargetFrameworkOverride", - // } - - public class FileInspectHandler : IHandler - { - public static string Handler => "fileInspect"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - try - { - string basePath = tokens["targetPath"]; - string outputName = tokens["targetPathName"]; - - string name = json["name"]?.ToString(); - string filename = json["file"].ToString(); - - foreach (KeyValuePair entry in tokens) - { - filename = filename.Replace($"%{entry.Key}%", entry.Value); - } - - string pathToFile = Path.Combine(basePath, filename); - bool doesFileExist = File.Exists(pathToFile); - - string fileContent = null; - - JArray expectations = json["expectations"]?.Value(); - - if (expectations != null) - { - foreach (JObject expectation in expectations.Children().OfType()) - { - string assertion = expectation["assertion"]?.Value()?.ToUpperInvariant(); - string text; - StringComparison comparison; - - switch (assertion) - { - case "EXISTS": - if (!doesFileExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to exist, but it did not", name: name); - } - break; - case "DOES_NOT_EXIST": - if (doesFileExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to not exist, but it did", name: name); - } - break; - case "CONTAINS": - text = expectation["text"]?.Value(); - if (!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out comparison)) - { - comparison = StringComparison.OrdinalIgnoreCase; - } - - if (!doesFileExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to contain \"{text}\" ({comparison}), but file did not exist", name: name); - } - - if (fileContent == null) - { - fileContent = File.ReadAllText(pathToFile); - } - - if (fileContent.IndexOf(text, comparison) < 0) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to contain \"{text}\" ({comparison}), but it did not", name: name); - } - - break; - case "DOES_NOT_CONTAIN": - text = expectation["text"].Value(); - if (!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out comparison)) - { - comparison = StringComparison.OrdinalIgnoreCase; - } - - if (!doesFileExist) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to not contain \"{text}\" ({comparison}), but file did not exist", name: name); - } - - if (fileContent == null) - { - fileContent = File.ReadAllText(pathToFile); - } - - if (fileContent.IndexOf(text, comparison) >= 0) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected file \"{filename}\" to not contain \"{text}\" ({comparison}), but it did", name: name); - } - - break; - } - - } - } - - return new GenericHandlerResult(watch.Elapsed, true, null); - } - catch (Exception ex) - { - return new GenericHandlerResult(watch.Elapsed, false, ex.Message); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - string filename = json["file"].ToString(); - - return $"File Inspection - inspecting file = \"{filename}\""; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/FindProcessHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/FindProcessHandler.cs deleted file mode 100644 index 1197b28388f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/FindProcessHandler.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - public class FindProcessHandler : IHandler - { - public static string Handler => "find"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - - try - { - string[] args = json["args"].Values().ToArray(); - - for (int i = 0; i < args.Length; ++i) - { - if (tokens.TryGetValue(args[i].Trim('%'), out string val)) - { - args[i] = val; - } - } - - string name = json["name"].ToString(); - Process p = Process.GetProcesses().FirstOrDefault(x => - { - ProcessStartInfo info = null; - - try - { - info = x.StartInfo; - } - catch - { - return false; - } - - return args.All(y => info.Arguments.Contains(y)); - }); - return new ExecuteHandlerResult(watch.Elapsed, p != null, p != null ? null : "Unable to find process", p, name); - } - finally - { - watch.Stop(); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - string[] args = json["args"].Values().ToArray(); - - for (int i = 0; i < args.Length; ++i) - { - if (tokens.TryGetValue(args[i].Trim('%'), out string val)) - { - args[i] = val; - } - } - - return $"Find process with args [{string.Join(", ", args)}]"; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/HttpRequestHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/HttpRequestHandler.cs deleted file mode 100644 index c038112ca60..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/HttpRequestHandler.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net.Http; -using System.Text; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - public class HttpRequestHandler : IHandler - { - public static string Handler => "httpRequest"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - - try - { - string name = json["name"]?.ToString(); - string url = json["url"].ToString(); - int status = json["statusCode"].Value(); - string verb = json["verb"].ToString(); - string body = json["body"]?.ToString(); - string requestMediaType = json["requestMediaType"]?.ToString(); - string requestEncoding = json["requestEncoding"]?.ToString(); - - HttpClient client = new HttpClient(); - HttpRequestMessage message = new HttpRequestMessage(new HttpMethod(verb), url); - - if (body != null) - { - if (!string.IsNullOrEmpty(requestEncoding)) - { - if (!string.IsNullOrEmpty(requestMediaType)) - { - message.Content = new StringContent(body, Encoding.GetEncoding(requestEncoding), requestMediaType); - } - else - { - message.Content = new StringContent(body, Encoding.GetEncoding(requestEncoding)); - } - } - else - { - message.Content = new StringContent(body); - } - } - - try - { - HttpResponseMessage response = client.SendAsync(message).Result; - bool success = status == (int)response.StatusCode; - string responseText = response.Content.ReadAsStringAsync().Result; - - JArray expectations = json["expectations"]?.Value(); - - if(expectations != null) - { - foreach(JObject expectation in expectations.Children().OfType()) - { - string assertion = expectation["assertion"]?.Value()?.ToUpperInvariant(); - string s, key; - StringComparison c; - IEnumerable values; - - switch (assertion) - { - case "RESPONSE_CONTAINS": - s = expectation["text"]?.Value(); - if(!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if(responseText.IndexOf(s, c) < 0) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected output to contain \"{s}\" ({c}), but it did not", name: name); - } - - break; - case "RESPONSE_DOES_NOT_CONTAIN": - s = expectation["text"]?.Value(); - if(!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if(responseText.IndexOf(s, c) > -1) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected output to NOT contain \"{s}\" ({c}), but it did", name: name); - } - - break; - case "RESPONSE_HEADER_CONTAINS": - key = expectation["key"]?.Value(); - s = expectation["text"]?.Value(); - if(!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if(!response.Headers.TryGetValues(key, out values)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to be present, but it was not", name: name); - } - - if(!values.Any(x => x.IndexOf(s, c) > -1)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to have a value \"{s}\", but it did not", name: name); - } - - break; - case "HAS_HEADER": - key = expectation["key"]?.Value(); - - if(!response.Headers.TryGetValues(key, out values)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to be present, but it was not", name: name); - } - - break; - - case "RESPONSE_HEADER_DOES_NOT_CONTAIN": - key = expectation["key"]?.Value(); - s = expectation["text"]?.Value(); - if(!Enum.TryParse(expectation["comparison"]?.Value() ?? "OrdinalIgnoreCase", out c)) - { - c = StringComparison.OrdinalIgnoreCase; - } - - if(!response.Headers.TryGetValues(key, out values)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to be present, but it was not", name: name); - } - - if(values.Any(x => x.IndexOf(s, c) > -1)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to NOT have a value \"{s}\", but it did", name: name); - } - - break; - case "DOES_NOT_HAVE_HEADER": - key = expectation["key"]?.Value(); - - if(response.Headers.TryGetValues(key, out values)) - { - return new ExecuteHandlerResult(watch.Elapsed, false, $"Expected a response header called \"{key}\" to NOT be present, but it was", name: name); - } - - break; - } - } - } - - return new GenericHandlerResult(watch.Elapsed, success, success ? null : $"Expected {status} but got {response.StatusCode}"); - } - catch (Exception ex) - { - return new GenericHandlerResult(watch.Elapsed, false, ex.Message); - } - } - finally - { - watch.Stop(); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - string url = json["url"].ToString(); - int status = json["statusCode"].Value(); - string verb = json["verb"].ToString(); - string body = json["body"]?.ToString(); - string requestMediaType = json["requestMediaType"]?.ToString(); - string requestEncoding = json["requestEncoding"]?.ToString(); - - return $"Web Request - {verb} {url} (Body? {body != null}, Encoding? {requestEncoding}, MediaType? {requestMediaType}) -> Expect {status}"; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/IHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/IHandler.cs deleted file mode 100644 index 3e0fc358ad4..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/IHandler.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - public interface IHandler - { - string HandlerName { get; } - - IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json); - - string Summarize(IReadOnlyDictionary tokens, JObject json); - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Handlers/TaskKillHandler.cs b/tools/legacy-tools/ProjectTestRunner/Handlers/TaskKillHandler.cs deleted file mode 100644 index 89337bb4a61..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Handlers/TaskKillHandler.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Newtonsoft.Json.Linq; -using ProjectTestRunner.HandlerResults; - -namespace ProjectTestRunner.Handlers -{ - public class TaskKillHandler : IHandler - { - public static string Handler => "taskkill"; - - public string HandlerName => Handler; - - public IHandlerResult Execute(IReadOnlyDictionary tokens, IReadOnlyList results, JObject json) - { - Stopwatch watch = Stopwatch.StartNew(); - - try - { - string targetName = json["name"].ToString(); - IHandlerResult result = results.FirstOrDefault(x => x.Name == targetName); - if (result is ExecuteHandlerResult xr) - { - xr.Kill(); - } - - return new GenericHandlerResult(watch.Elapsed, true, null); - } - finally - { - watch.Stop(); - } - } - - public string Summarize(IReadOnlyDictionary tokens, JObject json) - { - return "Kill process in named step " + json["name"].ToString(); - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Helpers/OutputHelperHelper.cs b/tools/legacy-tools/ProjectTestRunner/Helpers/OutputHelperHelper.cs deleted file mode 100644 index eada949ffe7..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Helpers/OutputHelperHelper.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.IO; -using System.Text; -using Xunit.Abstractions; - -namespace ProjectTestRunner.Helpers -{ - internal class OutputHelperHelper : TextWriter - { - private ITestOutputHelper _outputHelper; - - public OutputHelperHelper(ITestOutputHelper outputHelper) - { - _outputHelper = outputHelper; - } - - public override Encoding Encoding => Encoding.UTF8; - - public override void Write(char value) - { - } - - public override void WriteLine(string format, params object[] arg) - { - _outputHelper.WriteLine(format, arg); - } - - public override void WriteLine(string message) - { - _outputHelper.WriteLine(message ?? ""); - } - } -} \ No newline at end of file diff --git a/tools/legacy-tools/ProjectTestRunner/Helpers/PrettyTheoryAttribute.cs b/tools/legacy-tools/ProjectTestRunner/Helpers/PrettyTheoryAttribute.cs deleted file mode 100644 index a519bc00fb4..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Helpers/PrettyTheoryAttribute.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Runtime.CompilerServices; -using Xunit; - -namespace ProjectTestRunner.Helpers -{ - public class PrettyTheoryAttribute : TheoryAttribute - { - public PrettyTheoryAttribute([CallerMemberName] string memberName = null) - { - DisplayName = memberName; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Helpers/Proc.cs b/tools/legacy-tools/ProjectTestRunner/Helpers/Proc.cs deleted file mode 100644 index 2a3351b9008..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Helpers/Proc.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Diagnostics; - -namespace ProjectTestRunner.Helpers -{ - public class Proc - { - public static ProcessEx Run(string command, string args) - { - ProcessStartInfo psi = new ProcessStartInfo(command, args) - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true - }; - Process p = Process.Start(psi); - ProcessEx wrapper = new ProcessEx(p); - return wrapper; - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/Helpers/ProcessEx.cs b/tools/legacy-tools/ProjectTestRunner/Helpers/ProcessEx.cs deleted file mode 100644 index d662d3a453e..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Helpers/ProcessEx.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Diagnostics; -using System.Text; - -namespace ProjectTestRunner.Helpers -{ - public class ProcessEx - { - private readonly Process _process; - private readonly StringBuilder _stderr; - private readonly StringBuilder _stdout; - - public ProcessEx(Process p) - { - _stdout = new StringBuilder(); - _stderr = new StringBuilder(); - - _process = p; - p.OutputDataReceived += OnOutputData; - p.ErrorDataReceived += OnErrorData; - p.BeginOutputReadLine(); - p.BeginErrorReadLine(); - } - - public string Error => _stderr.ToString(); - - public string Output => _stdout.ToString(); - - public int ExitCode => _process.ExitCode; - - public static implicit operator Process(ProcessEx self) - { - return self._process; - } - - private void OnErrorData(object sender, DataReceivedEventArgs e) - { - _stderr.AppendLine(e.Data); - try - { - Console.Error.WriteLine(e.Data); - } - catch - { - } - } - - private void OnOutputData(object sender, DataReceivedEventArgs e) - { - _stdout.AppendLine(e.Data); - - try - { - Console.WriteLine(e.Data); - } - catch - { - } - } - - public bool WaitForExit(int milliseconds) - { - return _process.WaitForExit(milliseconds); - } - - public void WaitForExit() - { - _process.WaitForExit(); - } - } -} diff --git a/tools/legacy-tools/ProjectTestRunner/ProjectTestRunner.csproj b/tools/legacy-tools/ProjectTestRunner/ProjectTestRunner.csproj deleted file mode 100644 index e139621f275..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/ProjectTestRunner.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - Exe - $(NETCoreTargetFramework) - true - - - - - - - - - - - - Always - - - - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/CSharp/BoilerPlate.json b/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/CSharp/BoilerPlate.json deleted file mode 100644 index 113bdd0c07e..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/CSharp/BoilerPlate.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "skip": true, - "install": "Boilerplate.Templates::*", - "create": "bapi", - "name": "HTML Boilerplate (defaults)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp1.1/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/About", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/Contact", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/FSharp/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/FSharp/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/FSharp/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/VB/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/VB/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/3rdParty/VB/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Console.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Console.json deleted file mode 100644 index 34ce6cb9cb7..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Console.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "create": "console -f netcoreapp2.0 --no-restore", - "name": "Console (2.0 framework)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "expectations": [ - { - "assertion": "output_contains", - "text": "hello world" - } - ] - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Library.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Library.json deleted file mode 100644 index 4aefd01aeec..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Common/Library.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "create": "classlib --no-restore", - "name": "Console (default framework)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Mvc.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Mvc.json deleted file mode 100644 index c5c55f9144a..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Mvc.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "skip": true, - "create": "mvc -f netcoreapp2.0 --no-restore", - "name": "MVC (C#, 2.0 framework, default auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "directoryInspect", - "directory": "Areas", - "assertion": "does_not_exist" - }, - { - "handler": "directoryInspect", - "directory": "Extensions", - "assertion": "does_not_exist" - }, - { - "handler": "fileInspect", - "file": "urlRewrite.config", - "expectations": [ - { - "assertion": "does_not_exist" - } - ], - }, - { - "handler": "fileInspect", - "file": "Controllers/AccountController.cs", - "expectations": [ - { - "assertion": "does_not_exist" - } - ] - }, - { - "handler": "fileInspect", - "file": "%targetPathName%.csproj", - "expectations": [ - { - "assertion": "exists" - }, - { - "assertion": "does_not_contain", - "text": ".db" - }, - { - "assertion": "does_not_contain", - "text": "Microsoft.EntityFrameworkCore.Tools" - }, - { - "assertion": "does_not_contain", - "text": "Microsoft.VisualStudio.Web.CodeGeneration.Design" - }, - { - "assertion": "does_not_contain", - "text": "Microsoft.EntityFrameworkCore.Tools.DotNet" - }, - { - "assertion": "does_not_contain", - "text": "Microsoft.Extensions.SecretManager.Tools" - }, - ] - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/About", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/Contact", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/MvcIndividual.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/MvcIndividual.json deleted file mode 100644 index f8844c0fc2a..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/MvcIndividual.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "skip": true, - "create": "mvc -f netcoreapp2.0 -au Individual --KestrelPort 5000 --no-restore", - "name": "MVC (C#, 2.0 framework, local individual auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "directoryInspect", - "directory": "Extensions", - "assertion": "exists" - }, - { - "handler": "fileInspect", - "file": "Controllers/AccountController.cs", - "expectations": [ - { - "assertion": "exists" - } - ] - }, - { - "handler": "fileInspect", - "file": "%targetPathName%.csproj", - "expectations": [ - { - "assertion": "exists" - }, - { - "assertion": "contains", - "text": ".db" - }, - { - "assertion": "contains", - "text": "Microsoft.EntityFrameworkCore.Tools" - }, - { - "assertion": "contains", - "text": "Microsoft.VisualStudio.Web.CodeGeneration.Design" - }, - { - "assertion": "contains", - "text": "Microsoft.EntityFrameworkCore.Tools.DotNet" - }, - { - "assertion": "contains", - "text": "Microsoft.Extensions.SecretManager.Tools" - }, - ] - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/About", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/Contact", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/RazorPages.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/RazorPages.json deleted file mode 100644 index 7e865c00623..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/RazorPages.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "skip": true, - "create": "razor -f netcoreapp2.0 --no-restore", - "name": "Razor Pages (C#, 2.0 framework, default auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/About", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Contact", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Web.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Web.json deleted file mode 100644 index d0264e9ed47..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/Web.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "skip": true, - "create": "web -f netcoreapp2.0 --no-restore", - "name": "Empty Web (C#, 2.0 framework, default auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/WebApi.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/WebApi.json deleted file mode 100644 index f8685bff0f4..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/CSharp/Defaults/Web/WebApi.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "skip": true, - "create": "api -f netcoreapp2.0 --no-restore", - "name": "WebAPI (C#, 2.0 framework, default auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/api/values", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 404, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Console.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Console.json deleted file mode 100644 index ecce01367b8..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Console.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "create": "console -f netcoreapp2.0 --language F# --no-restore", - "name": "Console (F#, 2.0 framework)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "expectations": [ - { - "assertion": "output_contains", - "text": "hello world" - } - ] - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Library.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Library.json deleted file mode 100644 index 81711b3ab02..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Common/Library.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "create": "classlib --language f# --no-restore", - "name": "Console (default framework)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Web/Mvc.json b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Web/Mvc.json deleted file mode 100644 index d229f116530..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/FSharp/Defaults/Web/Mvc.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "skip": true, - "create": "mvc -f netcoreapp2.0 --language F# --no-restore", - "name": "MVC (F#, 2.0 framework, default auth)", - "tasks": [ - { - "handler": "execute", - "command": "dotnet", - "args": "restore -s https://pkgs.dev.azure.com/dnceng/public/_packaging/myget-legacy/nuget/v3/index.json -s https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json", - "noExit": false, - "exitCode": 0 - }, - { - "handler": "execute", - "command": "dotnet", - "args": "build", - "noExit": false, - "exitCode": 0 - }, - { - "name": "RunApp", - "handler": "execute", - "command": "dotnet", - "args": "exec bin/Debug/netcoreapp2.0/%targetPathName%.dll", - "noExit": true, - "exitTimeout": 5000 - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/About", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "httpRequest", - "url": "http://localhost:5000/Home/Contact", - "statusCode": 200, - "verb": "GET" - }, - { - "handler": "taskkill", - "name": "RunApp" - } - ] -} diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/VB/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/VB/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/BuiltIn/VB/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/CSharp/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/CSharp/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/CSharp/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/FSharp/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/FSharp/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/FSharp/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/VB/.gitkeep b/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/VB/.gitkeep deleted file mode 100644 index 8d1c8b69c3f..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/TestCases/Extensions/VB/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/legacy-tools/ProjectTestRunner/Testing-your-templates.md b/tools/legacy-tools/ProjectTestRunner/Testing-your-templates.md deleted file mode 100644 index 8466183f14c..00000000000 --- a/tools/legacy-tools/ProjectTestRunner/Testing-your-templates.md +++ /dev/null @@ -1,222 +0,0 @@ -dotnet/templating repo includes the test framework (ProjectTestRunner) which allows automated testing for the custom templates. The source code is available in [tools subfolder](https://github.com/dotnet/templating/tree/main/tools/ProjectTestRunner). -The default test set includes the templates shipped with dotnet SDK, but tests can be setup for 3rd-party templates as long as the templates can be installed using `dotnet new --install