From cba8c1d89002701a46b30612f48aac7579b6cd75 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 6 Feb 2019 07:49:25 -0800 Subject: [PATCH 1/5] Update to MSbuild 16 and Core SDK to 3.0 Preview 2, remove obsolete tasks, targets, and tools Instead of porting all these obsolete tasks and tools to MSBuild 16 and .NET Core 3, I've removed them in favor of simplifying KoreBuild --- BuildTools.sln | 15 +- build/dependencies.props | 12 +- build/repo.props | 1 - build/repo.targets | 13 +- build/tasks/RepoTasks.csproj | 1 - .../tasks}/ZipArchive.cs | 0 docs/Logging.md | 10 - docs/PackageReferenceManagement.md | 87 ---- docs/Sdk.md | 31 -- files/KoreBuild/KoreBuild.sh | 23 +- files/KoreBuild/config/sdk.version | 2 +- files/KoreBuild/scripts/KoreBuild.psm1 | 22 +- korebuild.json | 2 +- .../BuildTools.Tasks/BuildTools.Tasks.props | 5 - .../SetEnvironmentVariable.cs | 41 -- modules/BuildTools.Tasks/UnzipArchive.cs | 101 ----- .../BuildTools.Tasks/UpdatePackageSource.cs | 76 ---- modules/BuildTools.Tasks/WaitForDebugger.cs | 48 --- modules/BuildTools.Tasks/module.targets | 21 +- modules/BundledPackages/BundledPackages.proj | 53 --- modules/BundledPackages/NuGet.config | 7 - .../KoreBuild.Tasks/CheckPackageReferences.cs | 150 ------- .../KoreBuild.Tasks/DisableSkipStrongName.cs | 70 ---- .../KoreBuild.Tasks/DownloadNuGetPackages.cs | 131 ------ .../KoreBuild.Tasks/EnableSkipStrongName.cs | 84 ---- .../GenerateDependenciesPropsFile.cs | 158 ------- .../GeneratePackageVersionPropsFile.cs | 91 ---- modules/KoreBuild.Tasks/InstallToolsets.cs | 175 -------- .../KoreBuild.Tasks/Internal/HashHelper.cs | 45 -- .../KoreBuild.Tasks/Internal/MSBuildLogger.cs | 200 --------- .../KoreBuild.Tasks/Internal/PackageInfo.cs | 19 - .../ProjectModel/DotNetCliReferenceInfo.cs | 24 -- .../ProjectModel/PackageReferenceInfo.cs | 30 -- .../ProjectModel/ProjectFrameworkInfo.cs | 22 - .../Internal/ProjectModel/ProjectInfo.cs | 45 -- .../ProjectModel/ProjectInfoFactory.cs | 166 -------- .../Internal/ProjectModel/SolutionInfo.cs | 26 -- .../ProjectModel/SolutionInfoFactory.cs | 73 ---- .../Internal/SimplePackageInstaller.cs | 92 ---- .../KoreBuild.Tasks/KoreBuild.Tasks.csproj | 4 - .../KoreBuild.Tasks}/KoreBuildSettings.cs | 0 modules/KoreBuild.Tasks/PackNuSpec.cs | 250 ----------- modules/KoreBuild.Tasks/PushNuGetPackages.cs | 154 ------- .../SkipStrongName/AssembliesFile.cs | 78 ---- .../SkipStrongName/AssemblySpecification.cs | 16 - .../SkipStrongName/RegistrySection.cs | 10 - .../KoreBuild.Tasks/SkipStrongName/Status.cs | 11 - .../SkipStrongName/StrongNameConfiguration.cs | 110 ----- .../SkipStrongName/WindowsRegistry.cs | 116 ------ modules/KoreBuild.Tasks/SkipStrongNames.xml | 9 - .../KoreBuild.Tasks/UpgradeDependencies.cs | 276 ------------ .../Utilities/DependencyVersionsFile.cs | 235 ----------- .../Utilities/PackageDownloadRequest.cs | 15 - .../Utilities/PackageDownloader.cs | 114 ----- .../Utilities/PackageVersionVariable.cs | 56 --- modules/KoreBuild.Tasks/module.props | 10 - modules/KoreBuild.Tasks/module.targets | 94 +---- .../build/Common.props | 2 +- .../UnzipArchiveTest.cs | 197 --------- test/BuildTools.Tasks.Tests/ZipArchiveTest.cs | 220 ---------- .../SimpleRepoTests.cs | 88 +--- .../CheckPackageReferenceTests.cs | 288 ------------- .../DependencyVersionsFileTests.cs | 117 ------ .../DownloadNuGetPackagesTests.cs | 106 ----- .../GenerateDependenciesPropsFileTests.cs | 151 ------- .../GeneratePackageVersionPropsFileTests.cs | 116 ------ .../InstallToolsetsTests.cs | 54 --- .../KoreBuild.Tasks.Tests.csproj | 6 - test/KoreBuild.Tasks.Tests/PackNuSpecTests.cs | 393 ------------------ .../SolutionInfoFactoryTests.cs | 96 ----- .../TestResources/lorem.bin | 1 - .../UpgradeDependenciesTests.cs | 254 ----------- .../RepoThatShouldFailToBuild/korebuild.json | 2 +- .../src/BadConsole/BadConsole.csproj | 2 +- testassets/RepoWithGlobalTool/korebuild.json | 2 +- .../GlobalConsoleTool.csproj | 2 +- testassets/SimpleRepo/Directory.Build.props | 5 +- .../SimpleRepo/build/Sample.Lineup.nuspec | 15 - testassets/SimpleRepo/build/repo.targets | 18 - testassets/SimpleRepo/build/sources.props | 5 - .../SimpleRepo/build/tasks/RepoTasks.csproj | 5 +- testassets/SimpleRepo/korebuild.json | 2 +- .../Simple.Sample/Simple.Sample.csproj | 2 +- .../src/Simple.CliTool/Simple.CliTool.csproj | 4 +- .../src/Simple.Lib/Simple.Lib.csproj | 3 +- .../test/Simple.Test/Simple.Test.csproj | 2 +- .../Commands/ApiBaselinesGenerateCommand.cs | 50 --- .../KoreBuild.Console/Commands/CommandBase.cs | 45 -- .../Commands/CommandContext.cs | 177 -------- .../Commands/DependenciesGenerateCommand.cs | 76 ---- .../Commands/DependenciesUpgradeCommand.cs | 99 ----- .../Commands/DockerBuildCommand.cs | 187 --------- .../Commands/DockerFiles/.dockerignore | 4 - .../Commands/DockerFiles/jessie.dockerfile | 19 - .../DockerFiles/winservercore.dockerfile | 20 - .../Commands/InstallToolsCommand.cs | 130 ------ .../Commands/InstallToolsetsCommand.cs | 74 ---- .../Commands/MSBuildCommand.cs | 124 ------ .../KoreBuild.Console/Commands/RootCommand.cs | 66 --- .../Commands/SubCommandBase.cs | 63 --- .../KoreBuild.Console.csproj | 18 - tools/KoreBuild.Console/Program.cs | 32 -- .../Reporter/ConsoleReporter.cs | 70 ---- tools/KoreBuild.Console/Reporter/IConsole.cs | 21 - tools/KoreBuild.Console/Reporter/IReporter.cs | 14 - .../Reporter/PhysicalConsole.cs | 36 -- version.props | 4 +- 107 files changed, 48 insertions(+), 7169 deletions(-) rename {modules/BuildTools.Tasks => build/tasks}/ZipArchive.cs (100%) delete mode 100644 docs/PackageReferenceManagement.md delete mode 100644 docs/Sdk.md delete mode 100644 modules/BuildTools.Tasks/SetEnvironmentVariable.cs delete mode 100644 modules/BuildTools.Tasks/UnzipArchive.cs delete mode 100644 modules/BuildTools.Tasks/UpdatePackageSource.cs delete mode 100644 modules/BuildTools.Tasks/WaitForDebugger.cs delete mode 100644 modules/BundledPackages/BundledPackages.proj delete mode 100644 modules/BundledPackages/NuGet.config delete mode 100644 modules/KoreBuild.Tasks/CheckPackageReferences.cs delete mode 100644 modules/KoreBuild.Tasks/DisableSkipStrongName.cs delete mode 100644 modules/KoreBuild.Tasks/DownloadNuGetPackages.cs delete mode 100644 modules/KoreBuild.Tasks/EnableSkipStrongName.cs delete mode 100644 modules/KoreBuild.Tasks/GenerateDependenciesPropsFile.cs delete mode 100644 modules/KoreBuild.Tasks/GeneratePackageVersionPropsFile.cs delete mode 100644 modules/KoreBuild.Tasks/InstallToolsets.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/HashHelper.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/MSBuildLogger.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/PackageInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/DotNetCliReferenceInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/PackageReferenceInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectFrameworkInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfoFactory.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfo.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfoFactory.cs delete mode 100644 modules/KoreBuild.Tasks/Internal/SimplePackageInstaller.cs rename {tools => modules/KoreBuild.Tasks}/KoreBuildSettings.cs (100%) delete mode 100644 modules/KoreBuild.Tasks/PackNuSpec.cs delete mode 100644 modules/KoreBuild.Tasks/PushNuGetPackages.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/AssembliesFile.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/AssemblySpecification.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/RegistrySection.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/Status.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/StrongNameConfiguration.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongName/WindowsRegistry.cs delete mode 100644 modules/KoreBuild.Tasks/SkipStrongNames.xml delete mode 100644 modules/KoreBuild.Tasks/UpgradeDependencies.cs delete mode 100644 modules/KoreBuild.Tasks/Utilities/DependencyVersionsFile.cs delete mode 100644 modules/KoreBuild.Tasks/Utilities/PackageDownloadRequest.cs delete mode 100644 modules/KoreBuild.Tasks/Utilities/PackageDownloader.cs delete mode 100644 modules/KoreBuild.Tasks/Utilities/PackageVersionVariable.cs delete mode 100644 test/BuildTools.Tasks.Tests/UnzipArchiveTest.cs delete mode 100644 test/BuildTools.Tasks.Tests/ZipArchiveTest.cs delete mode 100644 test/KoreBuild.Tasks.Tests/CheckPackageReferenceTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/DependencyVersionsFileTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/DownloadNuGetPackagesTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/GenerateDependenciesPropsFileTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/GeneratePackageVersionPropsFileTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/InstallToolsetsTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/PackNuSpecTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/SolutionInfoFactoryTests.cs delete mode 100644 test/KoreBuild.Tasks.Tests/TestResources/lorem.bin delete mode 100644 test/KoreBuild.Tasks.Tests/UpgradeDependenciesTests.cs delete mode 100644 testassets/SimpleRepo/build/Sample.Lineup.nuspec delete mode 100644 testassets/SimpleRepo/build/sources.props delete mode 100644 tools/KoreBuild.Console/Commands/ApiBaselinesGenerateCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/CommandBase.cs delete mode 100644 tools/KoreBuild.Console/Commands/CommandContext.cs delete mode 100644 tools/KoreBuild.Console/Commands/DependenciesGenerateCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/DependenciesUpgradeCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/DockerBuildCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/DockerFiles/.dockerignore delete mode 100644 tools/KoreBuild.Console/Commands/DockerFiles/jessie.dockerfile delete mode 100644 tools/KoreBuild.Console/Commands/DockerFiles/winservercore.dockerfile delete mode 100644 tools/KoreBuild.Console/Commands/InstallToolsCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/InstallToolsetsCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/MSBuildCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/RootCommand.cs delete mode 100644 tools/KoreBuild.Console/Commands/SubCommandBase.cs delete mode 100644 tools/KoreBuild.Console/KoreBuild.Console.csproj delete mode 100644 tools/KoreBuild.Console/Program.cs delete mode 100644 tools/KoreBuild.Console/Reporter/ConsoleReporter.cs delete mode 100644 tools/KoreBuild.Console/Reporter/IConsole.cs delete mode 100644 tools/KoreBuild.Console/Reporter/IReporter.cs delete mode 100644 tools/KoreBuild.Console/Reporter/PhysicalConsole.cs diff --git a/BuildTools.sln b/BuildTools.sln index 573e4b696..fb9817086 100644 --- a/BuildTools.sln +++ b/BuildTools.sln @@ -1,7 +1,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27121.1 -MinimumVisualStudioVersion = 15.0.26730.03 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.0.0 +MinimumVisualStudioVersion = 16.0.0.0 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A4F4353B-C3D2-40B0-909A-5B48A748EA76}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "files", "files", "{BF3E9C90-F129-4CE6-8F3B-F96831E4429B}" @@ -82,10 +82,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGetPackageVerifier", "NuG EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KoreBuild.Tasks.Tests", "test\KoreBuild.Tasks.Tests\KoreBuild.Tasks.Tests.csproj", "{A3A81E93-0157-406F-A43C-C163F7F781A9}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{B16B5072-3A0B-4527-8AB5-1C73A51684F7}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KoreBuild.Console", "tools\KoreBuild.Console\KoreBuild.Console.csproj", "{02F548A6-B0E9-4F09-BC03-812FC3C8F0D2}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiCheckForwardDestination", "test\ApiCheckForwardDestination\ApiCheckForwardDestination.csproj", "{605F0478-A9D2-4A8A-BB38-9D5DC132FBB5}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NuGetPackageVerifier.Tests", "test\NuGetPackageVerifier.Tests\NuGetPackageVerifier.Tests.csproj", "{439CC7A3-F6E6-46B8-B6A0-05E22E558FC2}" @@ -148,10 +144,6 @@ Global {A3A81E93-0157-406F-A43C-C163F7F781A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {A3A81E93-0157-406F-A43C-C163F7F781A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {A3A81E93-0157-406F-A43C-C163F7F781A9}.Release|Any CPU.Build.0 = Release|Any CPU - {02F548A6-B0E9-4F09-BC03-812FC3C8F0D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {02F548A6-B0E9-4F09-BC03-812FC3C8F0D2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {02F548A6-B0E9-4F09-BC03-812FC3C8F0D2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {02F548A6-B0E9-4F09-BC03-812FC3C8F0D2}.Release|Any CPU.Build.0 = Release|Any CPU {605F0478-A9D2-4A8A-BB38-9D5DC132FBB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {605F0478-A9D2-4A8A-BB38-9D5DC132FBB5}.Debug|Any CPU.Build.0 = Debug|Any CPU {605F0478-A9D2-4A8A-BB38-9D5DC132FBB5}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -179,7 +171,6 @@ Global {020ED083-4076-4711-A52B-2F89EA884F9B} = {BD3545FB-5520-43DF-B4F9-83BEA3A38ECA} {C0E43505-F8EB-4B7F-B84D-5961F9763945} = {BD3545FB-5520-43DF-B4F9-83BEA3A38ECA} {A3A81E93-0157-406F-A43C-C163F7F781A9} = {60A938B2-D95A-403C-AA7A-3683AD64DFA0} - {02F548A6-B0E9-4F09-BC03-812FC3C8F0D2} = {B16B5072-3A0B-4527-8AB5-1C73A51684F7} {605F0478-A9D2-4A8A-BB38-9D5DC132FBB5} = {60A938B2-D95A-403C-AA7A-3683AD64DFA0} {439CC7A3-F6E6-46B8-B6A0-05E22E558FC2} = {60A938B2-D95A-403C-AA7A-3683AD64DFA0} EndGlobalSection diff --git a/build/dependencies.props b/build/dependencies.props index d04b326e5..84b4eab37 100644 --- a/build/dependencies.props +++ b/build/dependencies.props @@ -10,27 +10,27 @@ 0.10.0-beta6 4.7.99 - 10.0.1 + 12.0.1 4.7.0-rtm.5148 4.7.0-rtm.5148 2.2.7 - 2.3.1 - 2.3.1 + 2.4.1 + 2.4.1 - 15.9.19 + 16.0.0-preview.383 $(MicrosoftBuildPackageVersion) $(MicrosoftBuildPackageVersion) $(MicrosoftBuildPackageVersion) 9.0.1 - 4.9.0-preview3.5473 + 5.0.0-preview1.5663 diff --git a/build/repo.props b/build/repo.props index 603d5ec41..3b5ddf7e6 100644 --- a/build/repo.props +++ b/build/repo.props @@ -9,7 +9,6 @@ - diff --git a/build/repo.targets b/build/repo.targets index 1b58ae44f..3e2de62ee 100644 --- a/build/repo.targets +++ b/build/repo.targets @@ -66,17 +66,6 @@ Condition="'$(RepositoryBranch)' != '$(KoreBuildChannel)' AND '$(CI)' == 'true' AND '$(BUILD_REASON)' != 'PullRequest'" Code="BUILD1001" /> - - <_ToolsProjects Include="$(RepositoryRoot)tools\KoreBuild.Console\KoreBuild.Console.csproj"> - PublishDir=$(_KoreBuildIntermediateDir)\tools\%(Identity)\ - - - - - @@ -109,6 +98,8 @@ + + diff --git a/build/tasks/RepoTasks.csproj b/build/tasks/RepoTasks.csproj index 95cf0c2ce..ce5b0c8d8 100644 --- a/build/tasks/RepoTasks.csproj +++ b/build/tasks/RepoTasks.csproj @@ -18,7 +18,6 @@ - diff --git a/modules/BuildTools.Tasks/ZipArchive.cs b/build/tasks/ZipArchive.cs similarity index 100% rename from modules/BuildTools.Tasks/ZipArchive.cs rename to build/tasks/ZipArchive.cs diff --git a/docs/Logging.md b/docs/Logging.md index 580ad35b6..610222c38 100644 --- a/docs/Logging.md +++ b/docs/Logging.md @@ -8,13 +8,3 @@ KoreBuild produces log files to $(RepositoryRoot)/artifacts/logs. The following Using `build.cmd -Verbose` will produce a binary log file to artifacts/logs/msbuild.binlog. See for details. - -## TeamCity Logger - -KoreBuild can produce log messages for TeamCity by using . - -To configure this, - -1. Download the logger from JetBrains. https://github.com/JetBrains/TeamCity.MSBuild.Logger#download -2. Install this on CI agents. -3. Set the environment variable `KOREBUILD_TEAMCITY_LOGGER` to the file path of TeamCity.MSBuild.Logger.dll on CI agents. diff --git a/docs/PackageReferenceManagement.md b/docs/PackageReferenceManagement.md deleted file mode 100644 index 2c5203df7..000000000 --- a/docs/PackageReferenceManagement.md +++ /dev/null @@ -1,87 +0,0 @@ -PackageReference management ---------------------------- - -## Usage - -KoreBuild includes tools to help you automatically update your `dependencies.props` files. - -#### Generating a dependencies.props file - -On an existing project, you can execute the following command: -``` -run.ps1 generate deps -``` - -This will update csproj files and overwrite your build/dependencies.props file with variables. - -#### Updating dependencies.props - -KoreBuild can help you automatically update the `build/dependencies.props` file in your repo by using a lineup package. - -On command line, you can then execute -``` -run.ps1 upgrade deps -``` - -This command requires you set a few properties so the command can download a remote package and use that as the source -of version information. Most aspnetcore repos will set this in `build/repo.props` - -```xml - - Internal.AspNetCore.Universe.Lineup - - 2.1.0-* - https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json - -``` - -The lineup package itself contains a file that lists all version, and is itself also packaged under `build/dependencies.props`. The `upgrade deps` command will update any matching variables from the lineup package in the local copy of build/dependencies.props. - -## Restrictions on PackageReference usage - -To manage the complexity of keeping PackageReference versions consistent within a repo and between multiple repos, KoreBuild will enforce the following patterns for using PackageReference. - -#### 1. build/dependencies.props - -Each repository should have this file, and it should look like this. - -```xml - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - - 10.0.1 - 15.3.0 - 4.7.49 - 2.3.0 - - - - 10.0.1 - - -``` - -The `` section is for variables which should be automatically updated. - -The `` section is for variables which upgrade automation should not touch. - -### 2. PackageReference's should use variables to set versions - -All .csproj files should set the version of a package reference like this: - -```xml - - - -``` - -#### Opt-out of restrictions - -To opt-out of these restrictions, projects should add this to the `build/repo.props` file in their repository. -```xml - - true - -``` diff --git a/docs/Sdk.md b/docs/Sdk.md deleted file mode 100644 index 2cbca9efc..000000000 --- a/docs/Sdk.md +++ /dev/null @@ -1,31 +0,0 @@ -The Internal ASP.NET Core SDK -============================= - -The internal ASP.NET Core SDK provides features essential to producing ASP.NET Core itself. -It is not indended for general consumption beyond the ASP.NET Core team. - -## How to use it - -1. Change the first line of your .csproj files to - -```xml - -``` - -2. Add this to your NuGet.config -```xml - - - - - -``` - -3. Add a global.json file to your project with contents like this: -```json -{ - "msbuild-sdks": { - "Internal.AspNetCore.Sdk": "2.2.0-preview1-1234" - } -} -``` diff --git a/files/KoreBuild/KoreBuild.sh b/files/KoreBuild/KoreBuild.sh index ceaefa0c0..74eadaffb 100755 --- a/files/KoreBuild/KoreBuild.sh +++ b/files/KoreBuild/KoreBuild.sh @@ -72,15 +72,8 @@ invoke_korebuild_command(){ elif [ "$command" = "install-tools" ]; then __install_tools "$tools_source" "$dot_net_home" else - __ensure_dotnet - - kore_build_console_dll="$__korebuild_dir/tools/KoreBuild.Console.dll" - - __exec dotnet "$kore_build_console_dll" "$command" \ - --tools-source "$tools_source" \ - --dotnet-home "$dot_net_home" \ - --repo-path "$repo_path" \ - "$@" + __error "Unrecognized command $command" + exit 1 fi } @@ -129,18 +122,6 @@ __install_tools() { # Set environment variables export PATH="$install_dir:$PATH" - - # This is a workaround for https://github.com/Microsoft/msbuild/issues/2914. - # Currently, the only way to configure the NuGetSdkResolver is with NuGet.config, which is not generally used in aspnet org projects. - # This project is restored so that it pre-populates the NuGet cache with SDK packages. - local restorerfile="$__korebuild_dir/modules/BundledPackages/BundledPackageRestorer.csproj" - local restorerfilelock="$NUGET_PACKAGES/internal.aspnetcore.sdk/$(__get_korebuild_version)/korebuild.sentinel" - if [[ -e "$restorerfile" ]] && [[ ! -e "$restorerfilelock" ]]; then - mkdir -p "$(dirname $restorerfilelock)" - touch "$restorerfilelock" - __exec dotnet msbuild -t:restore -v:q "$restorerfile" - fi - # end workaround } __show_version_info() { diff --git a/files/KoreBuild/config/sdk.version b/files/KoreBuild/config/sdk.version index c4267acea..c175478ef 100644 --- a/files/KoreBuild/config/sdk.version +++ b/files/KoreBuild/config/sdk.version @@ -1 +1 @@ -3.0.100-preview-009750 +3.0.100-preview-010184 diff --git a/files/KoreBuild/scripts/KoreBuild.psm1 b/files/KoreBuild/scripts/KoreBuild.psm1 index 06df4cb83..ca718ead5 100644 --- a/files/KoreBuild/scripts/KoreBuild.psm1 +++ b/files/KoreBuild/scripts/KoreBuild.psm1 @@ -221,18 +221,6 @@ function Install-Tools( else { Write-Host -ForegroundColor DarkGray ".NET Core SDK $version is already installed. Skipping installation." } - - # This is a workaround for https://github.com/Microsoft/msbuild/issues/2914. - # Currently, the only way to configure the NuGetSdkResolver is with NuGet.config, which is not generally used in aspnet org projects. - # This project is restored so that it pre-populates the NuGet cache with SDK packages. - $restorerfile = "$PSScriptRoot/../modules/BundledPackages/BundledPackageRestorer.csproj" - $restorerfilelock="$env:NUGET_PACKAGES/internal.aspnetcore.sdk/$(Get-KoreBuildVersion)/korebuild.sentinel" - if ((Test-Path $restorerfile) -and -not (Test-Path $restorerfilelock)) { - New-Item -ItemType Directory $(Split-Path -Parent $restorerfilelock) -ErrorAction Ignore | Out-Null - New-Item -ItemType File $restorerfilelock -ErrorAction Ignore | Out-Null - __exec $global:dotnet msbuild '-t:restore' '-v:q' "$restorerfile" - } - # end workaround } <# @@ -492,8 +480,14 @@ function Get-MSBuildPath() { } Write-Verbose "vswhere = $vswherePath $vswhereArgs" - - $installations = & $vswherePath @vswhereArgs | Out-String | ConvertFrom-Json + $vswhereOut = & $vswherePath @vswhereArgs | Out-String + try { + $installations = $vswhereOut | ConvertFrom-Json + } + catch { + Write-Host -f Red "vswhere output = $vswhereOut" + throw $_ + } $latest = $null if ($installations) { diff --git a/korebuild.json b/korebuild.json index d25839fd1..629b9c1d6 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "./tools/korebuild.schema.json", - "channel": "master" + "channel": "feature/vs2019" } diff --git a/modules/BuildTools.Tasks/BuildTools.Tasks.props b/modules/BuildTools.Tasks/BuildTools.Tasks.props index e32478c8d..9e797e8c6 100644 --- a/modules/BuildTools.Tasks/BuildTools.Tasks.props +++ b/modules/BuildTools.Tasks/BuildTools.Tasks.props @@ -7,11 +7,6 @@ - - - - - diff --git a/modules/BuildTools.Tasks/SetEnvironmentVariable.cs b/modules/BuildTools.Tasks/SetEnvironmentVariable.cs deleted file mode 100644 index 62ca1cc79..000000000 --- a/modules/BuildTools.Tasks/SetEnvironmentVariable.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -namespace Microsoft.AspNetCore.BuildTools -{ -#if SDK - public class Sdk_SetEnvironmentVariable : Task -#elif BuildTools - public class SetEnvironmentVariable : Task -#else -#error This must be built either for an SDK or for BuildTools -#endif - { - [Required] - public string Variable { get; set; } - - [Required] - public string Value { get; set; } - - public override bool Execute() - { - if (string.IsNullOrEmpty(Variable)) - { - Log.LogError($"{nameof(Variable)} cannot be null or an empty string"); - return false; - } - - var expandedValue = Environment.ExpandEnvironmentVariables(Value); - - Log.LogMessage("Setting environment variable '{0}' to '{1}'", Variable, expandedValue); - - Environment.SetEnvironmentVariable(Variable, expandedValue); - - return true; - } - } -} diff --git a/modules/BuildTools.Tasks/UnzipArchive.cs b/modules/BuildTools.Tasks/UnzipArchive.cs deleted file mode 100644 index 5a4f37861..000000000 --- a/modules/BuildTools.Tasks/UnzipArchive.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using ZipArchiveStream = System.IO.Compression.ZipArchive; -using IOFile = System.IO.File; - -namespace Microsoft.AspNetCore.BuildTools -{ - /// - /// Unzips an archive file. - /// -#if SDK - public class Sdk_UnzipArchive : Task -#elif BuildTools - public class UnzipArchive : Task -#else -#error This must be built either for an SDK or for BuildTools -#endif - { - /// - /// The file to unzip. - /// - [Required] - public string File { get; set; } - - /// - /// The directory where files will be unzipped. - /// - /// - [Required] - public string Destination { get; set; } - - /// - /// Overwrite if it exists. Defaults to false. - /// - public bool Overwrite { get; set; } = false; - - /// - /// Disables normalizing zip entry paths while extracting. - /// - public bool DisablePathNormalization { get; set; } = false; - - /// - /// The files that were unzipped. - /// - [Output] - public ITaskItem[] OutputFiles { get; set; } - - public override bool Execute() - { - if (!IOFile.Exists(File)) - { - Log.LogError("'{0}' does not exist", File); - return false; - } - - Directory.CreateDirectory(Destination); - - var output = new List(); - using (var stream = IOFile.OpenRead(File)) - using (var zip = new ZipArchiveStream(stream, ZipArchiveMode.Read)) - { - foreach (var entry in zip.Entries) - { - var entryPath = entry.FullName; - if (!DisablePathNormalization) - { - if (entry.FullName.IndexOf('\\') >= 0) - { - Log.LogMessage(null, null, null, File, 0, 0, 0, 0, MessageImportance.Low, - message: $"Zip entry '{entry.FullName}' has been normalized because it contains a backslash. Set DisablePathNormalization=true to disable this."); - entryPath = entry.FullName.Replace('\\', '/'); - } - } - - var fileDest = Path.Combine(Destination, entryPath); - var dirName = Path.GetDirectoryName(fileDest); - Directory.CreateDirectory(dirName); - - // Do not try to extract directories - if (Path.GetFileName(fileDest) != string.Empty) - { - entry.ExtractToFile(fileDest, Overwrite); - Log.LogMessage(MessageImportance.Low, "Extracted '{0}'", fileDest); - output.Add(new TaskItem(fileDest)); - } - } - } - - Log.LogMessage(MessageImportance.High, "Extracted {0} file(s) to '{1}'", output.Count, Destination); - OutputFiles = output.ToArray(); - - return true; - } - } -} diff --git a/modules/BuildTools.Tasks/UpdatePackageSource.cs b/modules/BuildTools.Tasks/UpdatePackageSource.cs deleted file mode 100644 index 07321a095..000000000 --- a/modules/BuildTools.Tasks/UpdatePackageSource.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Linq; -using System.Xml.Linq; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -namespace Microsoft.AspNetCore.BuildTools -{ - /// - /// Update or adds a NuGet feed to a NuGet.config file. It reads - /// and replaces or adds the feed named with . - /// -#if SDK - public class Sdk_UpdatePackageSource : Task -#elif BuildTools - public class UpdatePackageSource : Task -#else -#error This must be built either for an SDK or for BuildTools -#endif - { - [Required] - public string NuGetConfigPath { get; set; } - - [Required] - public string SourceName { get; set; } - - [Required] - public string SourceUri { get; set; } - - public override bool Execute() - { - if (string.IsNullOrEmpty(SourceName)) - { - Log.LogError("FeedName must not be empty"); - return false; - } - - if (string.IsNullOrEmpty(SourceUri)) - { - Log.LogError("PackageSource must not be empty"); - return false; - } - - var nugetConfig = XDocument.Load(NuGetConfigPath); - var packageSources = nugetConfig.Element("configuration")?.Element("packageSources"); - var addElements = packageSources?.Elements("add").ToList(); - - var valueToUpdate = addElements.FirstOrDefault(f => string.Equals(f.Attribute("key")?.Value, SourceName, StringComparison.OrdinalIgnoreCase)); - if (valueToUpdate == null) - { - Log.LogMessage("Adding feed '{0}' to '{1}'", SourceName, SourceUri); - packageSources.Add(new XElement("add", - new XAttribute("key", SourceName), - new XAttribute("value", SourceUri))); - } - else - { - Log.LogMessage("Updating feed '{0}' to '{1}'", SourceName, SourceUri); - valueToUpdate.SetAttributeValue("value", SourceUri); - } - - using (var file = new FileStream(NuGetConfigPath, FileMode.Create)) - { - nugetConfig.Save(file); - } - - Log.LogMessage("Saved changes to '{0}'", NuGetConfigPath); - - return true; - } - } -} diff --git a/modules/BuildTools.Tasks/WaitForDebugger.cs b/modules/BuildTools.Tasks/WaitForDebugger.cs deleted file mode 100644 index 43478090a..000000000 --- a/modules/BuildTools.Tasks/WaitForDebugger.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Diagnostics; -using System.Threading; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -namespace Microsoft.AspNetCore.BuildTools -{ -#if SDK - public class Sdk_WaitForDebugger : Task, ICancelableTask -#elif BuildTools - public class WaitForDebugger : Task -#else -#error This must be built either for an SDK or for BuildTools -#endif - { - private bool _canceled; - - public void Cancel() - { - _canceled = true; - } - - public override bool Execute() - { - Log.LogMessage(MessageImportance.High, $"Waiting for debugger. Process ID: {Process.GetCurrentProcess().Id}"); - - // 30 seconds - var maxTimeout = 30 * 1000; - var step = 150; - - while (!Debugger.IsAttached && maxTimeout > 0 && !_canceled) - { - Thread.Sleep(step); - maxTimeout -= step; - } - - if (!Debugger.IsAttached && !_canceled) - { - Log.LogMessage(MessageImportance.High, "Waiting for debugger timed out. Continuing execution."); - } - - return true; - } - } -} diff --git a/modules/BuildTools.Tasks/module.targets b/modules/BuildTools.Tasks/module.targets index b22749fea..ba36fd4a9 100644 --- a/modules/BuildTools.Tasks/module.targets +++ b/modules/BuildTools.Tasks/module.targets @@ -1,7 +1,7 @@ - $(PrepareDependsOn);_UseVolatileFeed;ResolveCommitHash + $(PrepareDependsOn);ResolveCommitHash @@ -62,23 +62,4 @@ Generates resource files Condition="'@(Solutions)' != ''" /> - - - <_UpdateFeeds Include="ARTIFACTS" Value="$(NUGET_VOLATILE_FEED_ARTIFACTS)" Condition="'$(NUGET_VOLATILE_FEED_ARTIFACTS)' != ''" /> - <_UpdateFeeds Include="AspNetCore" Value="$(NUGET_VOLATILE_FEED_AspNetCore)" Condition="'$(NUGET_VOLATILE_FEED_AspNetCore)' != ''" /> - - - - - - diff --git a/modules/BundledPackages/BundledPackages.proj b/modules/BundledPackages/BundledPackages.proj deleted file mode 100644 index 6de9f34ef..000000000 --- a/modules/BundledPackages/BundledPackages.proj +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - false - false - - - - - - netcoreapp3.0 - true - - - - - - - -]]> - - - - - - - - - diff --git a/modules/BundledPackages/NuGet.config b/modules/BundledPackages/NuGet.config deleted file mode 100644 index b34426546..000000000 --- a/modules/BundledPackages/NuGet.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/modules/KoreBuild.Tasks/CheckPackageReferences.cs b/modules/KoreBuild.Tasks/CheckPackageReferences.cs deleted file mode 100644 index c99d5dd26..000000000 --- a/modules/KoreBuild.Tasks/CheckPackageReferences.cs +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using System.Linq; -using KoreBuild.Tasks.ProjectModel; -using KoreBuild.Tasks.Utilities; -using Microsoft.AspNetCore.BuildTools; -using Microsoft.Build.Construction; -using Microsoft.Build.Exceptions; -using Microsoft.Build.Framework; -using NuGet.Versioning; - -namespace KoreBuild.Tasks -{ - /// - /// Ensures MSBuild files use PackageReference responsibly. - /// - public class CheckPackageReferences : Microsoft.Build.Utilities.Task - { - /// - /// The solutions of csproj files to check. - /// - [Required] - public ITaskItem[] Projects { get; set; } - - /// - /// The file that contains the PropertyGroup of versions - /// - [Required] - public string DependenciesFile { get; set; } - - public string[] Properties { get; set; } - - public override bool Execute() - { - if (Projects == null || Projects.Length == 0) - { - Log.LogMessage(MessageImportance.Low, "No projects or solutions were found. Skipping PackageReference validation."); - return true; - } - - if (!File.Exists(DependenciesFile)) - { - Log.LogKoreBuildError(KoreBuildErrors.DependenciesFileDoesNotExist, $"Expected the dependencies file to exist at {DependenciesFile}"); - return false; - } - - if (!DependencyVersionsFile.TryLoad(DependenciesFile, out var depsFile)) - { - Log.LogError($"Could not load the dependencies file from {DependenciesFile}"); - return false; - } - - if (!depsFile.HasVersionsPropertyGroup) - { - Log.LogKoreBuildWarning(KoreBuildErrors.PackageRefPropertyGroupNotFound, $"No PropertyGroup with Label=\"{DependencyVersionsFile.PackageVersionsLabel}\" or Label=\"{DependencyVersionsFile.AutoPackageVersionsLabel}\" could be found in {DependenciesFile}"); - } - - foreach (var proj in Projects) - { - var ext = Path.GetExtension(proj.ItemSpec); - if (ext == ".sln") - { - var solutionProps = MSBuildListSplitter.GetNamedProperties(Properties); - var projectFiles = Projects.SelectMany(p => SolutionInfoFactory.GetProjects(p, solutionProps)).Distinct(); - foreach (var project in projectFiles) - { - VerifyPackageReferences(project, depsFile.VersionVariables); - } - } - else - { - VerifyPackageReferences(proj.ItemSpec, depsFile.VersionVariables); - } - } - - return !Log.HasLoggedErrors; - } - - private void VerifyPackageReferences(string filePath, IReadOnlyDictionary versionVariables) - { - ProjectRootElement doc; - try - { - doc = ProjectRootElement.Open(filePath); - } - catch (InvalidProjectFileException ex) - { - Log.LogError(null, null, null, filePath, 0, 0, 0, 0, message: "Invalid project file: " + ex.Message); - return; - } - - var packageReferences = doc.Items.Where(i => i.ItemType == "PackageReference"); - foreach (var pkgRef in packageReferences) - { - var id = pkgRef.Include; - - if (string.IsNullOrEmpty(id)) - { - // this node is an Update or Remove node - continue; - } - - var versionMetadata = pkgRef.Metadata.LastOrDefault(m => m.Name == "Version"); - var versionRaw = versionMetadata?.Value; - if (versionMetadata == null || string.IsNullOrEmpty(versionRaw)) - { - Log.LogKoreBuildError(pkgRef.Location.File, pkgRef.Location.Line, KoreBuildErrors.PackageReferenceDoesNotHaveVersion, $"PackageReference to {id} does not define a Version"); - continue; - } - - var versionIsVariable = - versionRaw != null - && versionRaw.Length > 3 - && versionRaw[0] == '$' - && versionRaw[1] == '(' - && versionRaw[versionRaw.Length - 1] == ')' - && versionRaw.IndexOf(')') == versionRaw.Length - 1; - - if (!versionIsVariable) - { - Log.LogKoreBuildError(pkgRef.Location.File, pkgRef.Location.Line, KoreBuildErrors.PackageRefHasLiteralVersion, "PackageReference must use an MSBuild variable to set the version."); - continue; - } - - var versionVarName = versionRaw.Substring(2, versionRaw.Length - 3); - - if (!versionVariables.TryGetValue(versionVarName, out var variable)) - { - Log.LogKoreBuildError(pkgRef.Location.File, pkgRef.Location.Line, KoreBuildErrors.VariableNotFoundInDependenciesPropsFile, $"The variable {versionRaw} could not be found in {DependenciesFile}"); - continue; - } - - var versionValue = variable.Version; - if (!VersionRange.TryParse(versionValue, out var nugetVersion)) - { - Log.LogKoreBuildError(pkgRef.Location.File, pkgRef.Location.Line, KoreBuildErrors.InvalidPackageVersion, $"PackageReference to {id} has an invalid version identifier: '{versionValue}'"); - continue; - } - - if (nugetVersion.IsFloating) - { - Log.LogKoreBuildError(pkgRef.Location.File, pkgRef.Location.Line, KoreBuildErrors.PackageRefHasFloatingVersion, $"PackageReference to {id} uses a floating version: '{versionValue}'"); - } - } - } - } -} diff --git a/modules/KoreBuild.Tasks/DisableSkipStrongName.cs b/modules/KoreBuild.Tasks/DisableSkipStrongName.cs deleted file mode 100644 index acb0d2345..000000000 --- a/modules/KoreBuild.Tasks/DisableSkipStrongName.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using KoreBuild.Tasks.SkipStrongNames; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Microsoft.Win32; - -namespace KoreBuild.Tasks -{ - public class DisableSkipStrongName : Task - { - [Required] - public string XmlFile { get; set; } - - public override bool Execute() - { - var configuration = new StrongNameConfiguration(AssembliesFile.Read(XmlFile)); - - return SkipDisable(configuration); - } - - private bool SkipDisable(StrongNameConfiguration configuration) - { - bool printedHeader = false; - - foreach (RegistrySection section in WindowsRegistry.Sections) - { - using (RegistryKey registryKey = WindowsRegistry.CreateWritableVerificationRegistryKey(section)) - { - if (registryKey == null) - { - Log.LogError($"Unable to open writable verification registry key for {section}."); - return false; - } - - foreach (var assembly in configuration.FilteredAssemblySpecifications[section]) - { - RegistryKey subKey = registryKey.OpenSubKey(assembly); - - if (subKey != null) - { - if (!printedHeader) - { - printedHeader = true; - Log.LogMessage("Deleting registry entries:"); - } - - Log.LogMessage($" {registryKey}\\{assembly}"); - subKey.Dispose(); - registryKey.DeleteSubKeyTree(assembly); - } - } - } - } - - if (!printedHeader) - { - Log.LogMessage("Skip Strong Names is already disabled."); - } - else - { - Log.LogMessage(""); - Log.LogMessage("Skip Strong Names was successfully disabled."); - } - - return true; - } - } -} diff --git a/modules/KoreBuild.Tasks/DownloadNuGetPackages.cs b/modules/KoreBuild.Tasks/DownloadNuGetPackages.cs deleted file mode 100644 index e69cb71f1..000000000 --- a/modules/KoreBuild.Tasks/DownloadNuGetPackages.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using NuGet.Build; -using NuGet.Packaging.Core; -using NuGet.Versioning; - -namespace KoreBuild.Tasks -{ - /// - /// Downloads NuGet packages in parallel. - /// - public class DownloadNuGetPackages : Microsoft.Build.Utilities.Task, ICancelableTask - { - private readonly CancellationTokenSource _cts = new CancellationTokenSource(); - - /// - /// The NuGet packages to download. Expected form: - /// - /// ItemSpec = PackageID - /// - /// Metadata: - /// Version = the exact package version to download - /// Source = the NuGet feed (remote or folder) - /// - [Required] - public ITaskItem[] Packages { get; set; } - - /// - /// The directory for download NuGet files. The task will write files to $(DestinationFolder)/$(PackageId.ToLower()).$(Version).nupkg - /// - [Required] - public string DestinationFolder { get; set; } - - /// - /// The package files that were downloaded. - /// - [Output] - public ITaskItem[] Files { get; set; } - - /// - /// The maximum amount of time to allow for downloading packages. - /// - public int TimeoutSeconds { get; set; } = 60 * 5; - - public void Cancel() => _cts.Cancel(); - - public override bool Execute() - { - return ExecuteAsync().Result; - } - - public async Task ExecuteAsync() - { - DestinationFolder = DestinationFolder.Replace('\\', '/'); - - var requests = new List(); - var files = new List(); - var downloadCount = 0; - foreach (var item in Packages) - { - var id = item.ItemSpec; - var rawVersion = item.GetMetadata("Version"); - if (!NuGetVersion.TryParse(rawVersion, out var version)) - { - Log.LogError($"Package '{id}' has an invalid 'Version' metadata value: '{rawVersion}'."); - return false; - } - - var source = item.GetMetadata("Source"); - if (string.IsNullOrEmpty(source)) - { - Log.LogError($"Package '{id}' is missing the 'Source' metadata value."); - return false; - } - - var outputPath = Path.Combine(DestinationFolder, $"{id.ToLowerInvariant()}.{version.ToNormalizedString()}.nupkg"); - - files.Add(new TaskItem(outputPath)); - if (File.Exists(outputPath)) - { - Log.LogMessage($"Skipping {id} {version}. Already exists in '{outputPath}'"); - continue; - } - else - { - downloadCount++; - - var request = new PackageDownloadRequest - { - Identity = new PackageIdentity(id, version), - OutputPath = outputPath, - Sources = source.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries), - }; - - requests.Add(request); - } - } - - Files = files.ToArray(); - - if (downloadCount == 0) - { - Log.LogMessage("All packages are downloaded."); - return true; - } - - Directory.CreateDirectory(DestinationFolder); - var logger = new MSBuildLogger(Log); - var timeout = TimeSpan.FromSeconds(TimeoutSeconds); - var downloader = new PackageDownloader(logger); - var timer = Stopwatch.StartNew(); - - var result = await downloader.DownloadPackagesAsync(requests, timeout, _cts.Token); - - timer.Stop(); - logger.LogMinimal($"Finished downloading {requests.Count} package(s) in {timer.ElapsedMilliseconds}ms"); - return result; - } - } -} diff --git a/modules/KoreBuild.Tasks/EnableSkipStrongName.cs b/modules/KoreBuild.Tasks/EnableSkipStrongName.cs deleted file mode 100644 index 53ffd31ce..000000000 --- a/modules/KoreBuild.Tasks/EnableSkipStrongName.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; -using System.Runtime.InteropServices; -using KoreBuild.Tasks.SkipStrongNames; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Microsoft.Win32; - -namespace KoreBuild.Tasks -{ - public class EnableSkipStrongName : Task - { - [Required] - public string XmlFile { get; set; } - - public override bool Execute() - { - var configuration = new StrongNameConfiguration(AssembliesFile.Read(XmlFile)); - - return SkipEnable(configuration); - } - - private bool SkipEnable(StrongNameConfiguration configuration) - { - if (!File.Exists(XmlFile)) - { - Log.LogError("The XmlFile given must exist."); - return false; - } - - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - Log.LogError("Strongname tasks should only be run on Windows."); - return false; - } - - bool printedHeader = false; - - foreach (RegistrySection section in WindowsRegistry.Sections) - { - using (RegistryKey registryKey = WindowsRegistry.CreateWritableVerificationRegistryKey(section)) - { - if (registryKey == null) - { - Log.LogError($"Unable to open writable verification registry key for {section}."); - return false; - } - - foreach (var assembly in configuration.FilteredAssemblySpecifications[section]) - { - using (RegistryKey subKey = registryKey.OpenSubKey(assembly)) - { - if (subKey == null) - { - if (!printedHeader) - { - printedHeader = true; - Log.LogMessage("Adding registry entries:"); - } - - Log.LogMessage($" {registryKey}\\{assembly}"); - registryKey.CreateSubKey(assembly); - } - } - } - } - } - - if (!printedHeader) - { - Log.LogMessage("Skip Strong Names is already enabled."); - } - else - { - Log.LogMessage(""); - Log.LogMessage("Skip Strong Names was successfully enabled."); - } - - return true; - } - } -} diff --git a/modules/KoreBuild.Tasks/GenerateDependenciesPropsFile.cs b/modules/KoreBuild.Tasks/GenerateDependenciesPropsFile.cs deleted file mode 100644 index 149fc5b8d..000000000 --- a/modules/KoreBuild.Tasks/GenerateDependenciesPropsFile.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using KoreBuild.Tasks.ProjectModel; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -namespace KoreBuild.Tasks -{ - /// - /// Generates the build/dependencies.props file base on your current project, - /// and updates all PackageReferences in and to use MSBuild variables. - /// - public class GenerateDependenciesPropsFile : Microsoft.Build.Utilities.Task, ICancelableTask - { - private readonly CancellationTokenSource _cts = new CancellationTokenSource(); - - /// - /// The projects to update - /// - [Required] - public ITaskItem[] Projects { get; set; } - - /// - /// other files to update that may have PackageReferences in them - /// - public ITaskItem[] OtherImports { get; set; } - - /// - /// Location of the dependenices.props file - /// - [Required] - public string DependenciesFile { get; set; } - - /// - /// Additional properties to use when evaluating the projects - /// - public string[] Properties { get; set; } - - public void Cancel() - { - _cts.Cancel(); - } - - public override bool Execute() - { - var unifiedPackageList = new Dictionary(StringComparer.OrdinalIgnoreCase); - - var projects = new ProjectInfoFactory(Log).CreateMany(Projects, Properties, false, _cts.Token); - var packageRefs = projects.SelectMany(p => p.Frameworks).SelectMany(f => f.Dependencies); - - foreach (var packageRef in packageRefs) - { - if (packageRef.Value.IsImplicitlyDefined) - { - // skip PackageReferences added by the SDK - continue; - } - - if (packageRef.Value.NoWarn.Contains(KoreBuildErrors.Prefix + KoreBuildErrors.ConflictingPackageReferenceVersions)) - { - // Make it possible to suppress version conflicts while generating this file. - continue; - } - - if (unifiedPackageList.TryGetValue(packageRef.Value.Id, out var other)) - { - if (other.Version != packageRef.Value.Version) - { - Log.LogKoreBuildError(KoreBuildErrors.ConflictingPackageReferenceVersions, $"Conflicting dependency versions for {packageRef.Value.Id}: {other.Project.FileName} references '{other.Version}' but {packageRef.Value.Project.FileName} references '{packageRef.Value.Version}'"); - } - } - else - { - unifiedPackageList.Add(packageRef.Value.Id, packageRef.Value); - Log.LogMessage(MessageImportance.Low, $"Found {packageRef.Value.Id} = {packageRef.Value.Version}"); - } - } - - if (Log.HasLoggedErrors) - { - return false; - } - - var items = unifiedPackageList.Values.Select(p => new TaskItem(p.Id, new Hashtable { ["Version"] = p.Version })).ToArray(); - - var task = new GeneratePackageVersionPropsFile - { - AddOverrideImport = true, - SuppressVariableLabels = true, - Packages = items, - BuildEngine = BuildEngine, - HostObject = HostObject, - OutputPath = DependenciesFile, - }; - - if (!task.Execute()) - { - return false; - } - - var otherImports = OtherImports != null - ? OtherImports.Select(p => p.ItemSpec) - : Array.Empty(); - - foreach (var proj in projects.Select(p => p.FullPath).Concat(otherImports)) - { - var project = ProjectRootElement.Open(proj, ProjectCollection.GlobalProjectCollection, preserveFormatting: true); - var changed = false; - foreach (var item in project.Items.Where(i => i.ItemType == "PackageReference")) - { - var noWarn = item.Metadata.FirstOrDefault(m => m.Name == "NoWarn"); - if (noWarn != null && noWarn.Value.Contains(KoreBuildErrors.Prefix + KoreBuildErrors.ConflictingPackageReferenceVersions)) - { - continue; - } - - var versionMetadata = item.Metadata.LastOrDefault(p => p.Name == "Version"); - if (versionMetadata != null && versionMetadata.Value.StartsWith("$(")) - { - continue; - } - changed = true; - - var varName = $"$({DependencyVersionsFile.GetVariableName(item.Include)})"; - if (versionMetadata == null) - { - item.AddMetadata("Version", varName, expressAsAttribute: true); - } - else - { - versionMetadata.Value = varName; - } - } - - if (changed) - { - Log.LogMessage(MessageImportance.High, $"Updated {proj}"); - project.Save(proj); - } - else - { - Log.LogMessage(MessageImportance.Normal, $"Skipping {proj}. Already up to date."); - } - } - - return !Log.HasLoggedErrors; - } - } -} diff --git a/modules/KoreBuild.Tasks/GeneratePackageVersionPropsFile.cs b/modules/KoreBuild.Tasks/GeneratePackageVersionPropsFile.cs deleted file mode 100644 index 38c34cf15..000000000 --- a/modules/KoreBuild.Tasks/GeneratePackageVersionPropsFile.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -namespace KoreBuild.Tasks -{ - public class GeneratePackageVersionPropsFile : Task - { - [Required] - public ITaskItem[] Packages { get; set; } - - [Required] - public string OutputPath { get; set; } - - public bool AddOverrideImport { get; set; } - - public string[] AdditionalImports { get; set; } - - public bool SuppressVariableLabels { get; set; } - - public override bool Execute() - { - OutputPath = OutputPath.Replace('\\', '/'); - Directory.CreateDirectory(Path.GetDirectoryName(OutputPath)); - - DependencyVersionsFile depsFile; - if (File.Exists(OutputPath)) - { - if (!DependencyVersionsFile.TryLoad(OutputPath, out depsFile)) - { - depsFile = DependencyVersionsFile.Create(AddOverrideImport, AdditionalImports); - Log.LogWarning($"Could not load the existing deps file from {OutputPath}. This file will be overwritten."); - } - } - else - { - depsFile = DependencyVersionsFile.Create(AddOverrideImport, AdditionalImports); - } - - var varNames = new HashSet(); - foreach (var pkg in Packages) - { - var packageVersion = pkg.GetMetadata("Version"); - - if (string.IsNullOrEmpty(packageVersion)) - { - Log.LogError("Package {0} is missing the Version metadata", pkg.ItemSpec); - continue; - } - - string packageVarName; - if (!string.IsNullOrEmpty(pkg.GetMetadata("VariableName"))) - { - packageVarName = pkg.GetMetadata("VariableName"); - if (!packageVarName.EndsWith("Version", StringComparison.Ordinal)) - { - Log.LogError("VariableName for {0} must end in 'Version'", pkg.ItemSpec); - continue; - } - } - else - { - packageVarName = DependencyVersionsFile.GetVariableName(pkg.ItemSpec); - } - - if (varNames.Contains(packageVarName)) - { - Log.LogError("Multiple packages would produce {0} in the generated dependencies.props file. Set VariableName to differentiate the packages manually", packageVarName); - continue; - } - - var item = depsFile.Update(packageVarName, packageVersion); - if (!SuppressVariableLabels) - { - item.SetLabel(pkg.ItemSpec); - } - } - - depsFile.Save(OutputPath); - Log.LogMessage(MessageImportance.Normal, $"Generated {OutputPath}"); - return !Log.HasLoggedErrors; - } - } -} diff --git a/modules/KoreBuild.Tasks/InstallToolsets.cs b/modules/KoreBuild.Tasks/InstallToolsets.cs deleted file mode 100644 index 079751513..000000000 --- a/modules/KoreBuild.Tasks/InstallToolsets.cs +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright(c) .NET Foundation.All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Framework; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Tasks -{ - /// - /// Installs toolset information as listed in korebuild.json - /// - public class InstallToolsets : Microsoft.Build.Utilities.Task - { - /// - /// The path to the korebuild.json file. - /// - [Required] - public string ConfigFile { get; set; } - - /// - /// Whether to install toolsets with or without user interation. - /// It will default prompting users to confirm and see installation steps. - /// - public bool QuietVSInstallation { get; set; } - - /// - /// Whether to upgrade existing toolsets. - /// It will default to only adding tools that were not previously installed. - /// - public bool UpgradeVSInstallation { get; set; } - - /// - /// Specifies what version of VS to install. - /// Defaults to Enterprise. - /// - public string VSProductVersionType { get; set; } = "Enterprise"; - - public override bool Execute() - { - return ExecuteAsync().GetAwaiter().GetResult(); - } - - public async Task ExecuteAsync() - { - if (!File.Exists(ConfigFile)) - { - Log.LogError($"Could not load the korebuild config file from '{ConfigFile}'"); - return false; - } - - var settings = KoreBuildSettings.Load(ConfigFile); - - if (settings?.Toolsets == null) - { - Log.LogMessage(MessageImportance.Normal, "No recognized toolsets specified."); - return true; - } - - foreach (var toolset in settings.Toolsets) - { - switch (toolset) - { - case KoreBuildSettings.VisualStudioToolset vs: - await InstallVsComponents(vs); - break; - // TODO support NodeJSToolset - default: - Log.LogWarning("Toolset checks not implemented for " + toolset.GetType().Name); - break; - } - } - - return !Log.HasLoggedErrors; - } - - private async Task InstallVsComponents(KoreBuildSettings.VisualStudioToolset vsToolset) - { - if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - if ((vsToolset.Required & ~KoreBuildSettings.RequiredPlatforms.Windows) != 0) - { - Log.LogError("Visual Studio is not available on non-Windows. Change korebuild.json to 'required: [\"windows\"]'."); - } - else - { - Log.LogMessage(MessageImportance.Low, "Skipping Visual Studio verification on non-Windows platforms."); - } - return; - } - - // Update the vs installation based on the product version specified. - var vs = VsWhere.FindLatestInstallation(includePrerelease: true, vsProductVersion: VSProductVersionType, log: Log); - - if (vs != null) - { - Log.LogMessage($"Found vs installation located at {vs.InstallationPath}"); - } - else - { - Log.LogMessage($"No vs installation found."); - } - - var vsExePath = await VsInstallerHelper.DownloadVsExe(Log, VSProductVersionType); - var vsJsonFilePath = VsInstallerHelper.CreateVsFileFromRequiredToolset(vsToolset, Log, VSProductVersionType); - - var args = GetVisualStudioArgs(vs, vsJsonFilePath); - - StartVsExe(vsExePath, args); - - // Cleanup temp files created. - try - { - File.Delete(vsExePath); - File.Delete(vsJsonFilePath); - } - catch (IOException ioe) - { - Log.LogWarning($"Could not delete vs installation files in temp directory: {ioe.Message}."); - } - - return; - } - - private string GetVisualStudioArgs(VsInstallation vs, string vsJsonFilePath) - { - var args = new List(); - - if (vs != null) - { - if (UpgradeVSInstallation) - { - args.Add("upgrade"); - } - else - { - args.Add("modify"); - } - args.Add("--installPath"); - args.Add($"{vs.InstallationPath}"); - } - - args.Add("--in"); - args.Add($"{vsJsonFilePath}"); - args.Add("--wait"); - args.Add("--norestart"); - - if (QuietVSInstallation) - { - args.Add("--quiet"); - } - return ArgumentEscaper.EscapeAndConcatenate(args); - } - - private void StartVsExe(string vsExePath, string args) - { - var psi = new ProcessStartInfo - { - FileName = vsExePath, - Arguments = args - }; - - Log.LogMessage($"Calling: {psi.FileName} {psi.Arguments}"); - - var process = Process.Start(psi); - - process.WaitForExit(); - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/HashHelper.cs b/modules/KoreBuild.Tasks/Internal/HashHelper.cs deleted file mode 100644 index 0973cf812..000000000 --- a/modules/KoreBuild.Tasks/Internal/HashHelper.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace KoreBuild.Tasks -{ - internal class HashHelper - { - public static string GetFileHash(string algorithmName, string filePath) - { - byte[] hash; - using (var stream = File.OpenRead(filePath)) - { - HashAlgorithm algorithm; - switch (algorithmName.ToUpperInvariant()) - { - case "SHA256": - algorithm = new SHA256Managed(); - break; - case "SHA384": - algorithm = new SHA384Managed(); - break; - case "SHA512": - algorithm = new SHA512Managed(); - break; - default: - throw new ArgumentOutOfRangeException($"Unsupported hash algoritm {algorithmName}", nameof(algorithm)); - } - hash = algorithm.ComputeHash(stream); - } - - var sb = new StringBuilder(); - foreach (var b in hash) - { - sb.AppendFormat("{0:X2}", b); - } - - return sb.ToString(); - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/MSBuildLogger.cs b/modules/KoreBuild.Tasks/Internal/MSBuildLogger.cs deleted file mode 100644 index 458bd698d..000000000 --- a/modules/KoreBuild.Tasks/Internal/MSBuildLogger.cs +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using NuGet.Common; - -namespace NuGet.Build -{ - /// - /// TaskLoggingHelper -> ILogger - /// - internal class MSBuildLogger : LoggerBase, Common.ILogger - { - private readonly TaskLoggingHelper _taskLogging; - - private delegate void LogMessageWithDetails(string subcategory, - string code, - string helpKeyword, - string file, - int lineNumber, - int columnNumber, - int endLineNumber, - int endColumnNumber, - MessageImportance importance, - string message, - params object[] messageArgs); - - private delegate void LogErrorWithDetails(string subcategory, - string code, - string helpKeyword, - string file, - int lineNumber, - int columnNumber, - int endLineNumber, - int endColumnNumber, - string message, - params object[] messageArgs); - - private delegate void LogMessageAsString(MessageImportance importance, - string message, - params object[] messageArgs); - - private delegate void LogErrorAsString(string message, - params object[] messageArgs); - - public MSBuildLogger(TaskLoggingHelper taskLogging) - { - _taskLogging = taskLogging ?? throw new ArgumentNullException(nameof(taskLogging)); - } - - public override void Log(ILogMessage message) - { - if (DisplayMessage(message.Level)) - { - if (RuntimeEnvironmentHelper.IsMono) - { - LogForMono(message); - return; - } - else - { - var logMessage = message as IRestoreLogMessage; - - if (logMessage == null) - { - logMessage = new RestoreLogMessage(message.Level, message.Message) - { - Code = message.Code, - FilePath = message.ProjectPath - }; - } - LogForNonMono(logMessage); - } - } - } - - /// - /// Log using with metadata for non mono platforms. - /// - private void LogForNonMono(IRestoreLogMessage message) - { - switch (message.Level) - { - case LogLevel.Error: - LogError(message, _taskLogging.LogError, _taskLogging.LogError); - break; - - case LogLevel.Warning: - LogError(message, _taskLogging.LogWarning, _taskLogging.LogWarning); - break; - - case LogLevel.Minimal: - LogMessage(message, MessageImportance.High, _taskLogging.LogMessage, _taskLogging.LogMessage); - break; - - case LogLevel.Information: - LogMessage(message, MessageImportance.Normal, _taskLogging.LogMessage, _taskLogging.LogMessage); - break; - - case LogLevel.Debug: - case LogLevel.Verbose: - default: - // Default to LogLevel.Debug and low importance - LogMessage(message, MessageImportance.Low, _taskLogging.LogMessage, _taskLogging.LogMessage); - break; - } - } - - /// - /// Log using basic methods to avoid missing methods on mono. - /// - private void LogForMono(ILogMessage message) - { - switch (message.Level) - { - case LogLevel.Error: - _taskLogging.LogError(message.Message); - break; - - case LogLevel.Warning: - _taskLogging.LogWarning(message.Message); - break; - - case LogLevel.Minimal: - _taskLogging.LogMessage(MessageImportance.High, message.Message); - break; - - case LogLevel.Information: - _taskLogging.LogMessage(MessageImportance.Normal, message.Message); - break; - - case LogLevel.Debug: - case LogLevel.Verbose: - default: - // Default to LogLevel.Debug and low importance - _taskLogging.LogMessage(MessageImportance.Low, message.Message); - break; - } - - return; - } - - private void LogMessage(IRestoreLogMessage logMessage, - MessageImportance importance, - LogMessageWithDetails logWithDetails, - LogMessageAsString logAsString) - { - if (logMessage.Code > NuGetLogCode.Undefined) - { - // NuGet does not currently have a subcategory while throwing logs, hence string.Empty - logWithDetails(string.Empty, - Enum.GetName(typeof(NuGetLogCode), logMessage.Code), - Enum.GetName(typeof(NuGetLogCode), logMessage.Code), - logMessage.FilePath, - logMessage.StartLineNumber, - logMessage.StartColumnNumber, - logMessage.EndLineNumber, - logMessage.EndColumnNumber, - importance, - logMessage.Message); - } - else - { - logAsString(importance, logMessage.Message); - } - } - - private void LogError(IRestoreLogMessage logMessage, - LogErrorWithDetails logWithDetails, - LogErrorAsString logAsString) - { - if (logMessage.Code > NuGetLogCode.Undefined) - { - // NuGet does not currently have a subcategory while throwing logs, hence string.Empty - logWithDetails(string.Empty, - Enum.GetName(typeof(NuGetLogCode), logMessage.Code), - Enum.GetName(typeof(NuGetLogCode), logMessage.Code), - logMessage.FilePath, - logMessage.StartLineNumber, - logMessage.StartColumnNumber, - logMessage.EndLineNumber, - logMessage.EndColumnNumber, - logMessage.Message); - } - else - { - logAsString(logMessage.Message); - } - } - - public override System.Threading.Tasks.Task LogAsync(ILogMessage message) - { - Log(message); - - return System.Threading.Tasks.Task.FromResult(0); - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/PackageInfo.cs b/modules/KoreBuild.Tasks/Internal/PackageInfo.cs deleted file mode 100644 index b976aabfa..000000000 --- a/modules/KoreBuild.Tasks/Internal/PackageInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using NuGet.Packaging.Core; - -namespace KoreBuild.Tasks.Internal -{ - public class PackageInfo - { - public PackageIdentity Identity { get; set; } - - public string PackagePath { get; set; } - - public override string ToString() - { - return Identity.ToString(); - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/DotNetCliReferenceInfo.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/DotNetCliReferenceInfo.cs deleted file mode 100644 index d4a9712fd..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/DotNetCliReferenceInfo.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class DotNetCliReferenceInfo - { - public DotNetCliReferenceInfo(string id, string version) - { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(nameof(id)); - } - - Id = id; - Version = version; - } - - public string Id { get; } - public string Version { get; } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/PackageReferenceInfo.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/PackageReferenceInfo.cs deleted file mode 100644 index 63a9edde8..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/PackageReferenceInfo.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class PackageReferenceInfo - { - public PackageReferenceInfo(string id, string version, bool isImplicitlyDefined, IReadOnlyList noWarn) - { - if (string.IsNullOrEmpty(id)) - { - throw new ArgumentException(nameof(id)); - } - - Id = id; - Version = version; - IsImplicitlyDefined = isImplicitlyDefined; - NoWarn = noWarn; - } - - public string Id { get; } - public string Version { get; } - public bool IsImplicitlyDefined { get; } - public IReadOnlyList NoWarn { get; } - public ProjectInfo Project { get; internal set; } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectFrameworkInfo.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectFrameworkInfo.cs deleted file mode 100644 index ee0f9d3db..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectFrameworkInfo.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using NuGet.Frameworks; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class ProjectFrameworkInfo - { - public ProjectFrameworkInfo(NuGetFramework targetFramework, IReadOnlyDictionary dependencies) - { - TargetFramework = targetFramework ?? throw new ArgumentNullException(nameof(targetFramework)); - Dependencies = dependencies ?? throw new ArgumentNullException(nameof(dependencies)); - } - - public NuGetFramework TargetFramework { get; } - public IReadOnlyDictionary Dependencies { get; } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfo.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfo.cs deleted file mode 100644 index 95dc0780f..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfo.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class ProjectInfo - { - public ProjectInfo(string fullPath, - string projectExtensionsPath, - IReadOnlyList frameworks, - IReadOnlyList tools) - { - if (!Path.IsPathRooted(fullPath)) - { - throw new ArgumentException("Path must be absolute", nameof(fullPath)); - } - - Frameworks = frameworks ?? throw new ArgumentNullException(nameof(frameworks)); - Tools = tools ?? throw new ArgumentNullException(nameof(tools)); - - FullPath = fullPath; - FileName = Path.GetFileName(fullPath); - Directory = Path.GetDirectoryName(FullPath); - ProjectExtensionsPath = projectExtensionsPath ?? Path.Combine(Directory, "obj"); - - foreach (var dep in frameworks.SelectMany(f => f.Dependencies)) - { - dep.Value.Project = this; - } - } - - public string FullPath { get; } - public string FileName { get; } - public string ProjectExtensionsPath { get; } - public string Directory { get; } - - public IReadOnlyList Frameworks { get; } - public IReadOnlyList Tools { get; } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfoFactory.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfoFactory.cs deleted file mode 100644 index 65e5879dc..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/ProjectInfoFactory.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -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 Microsoft.AspNetCore.BuildTools; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Execution; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using NuGet.Frameworks; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class ProjectInfoFactory - { - private readonly TaskLoggingHelper _logger; - - public ProjectInfoFactory(TaskLoggingHelper logger) - { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - } - - public IReadOnlyList CreateMany(ITaskItem[] projectItems, string[] properties, bool policyDesignBuild, CancellationToken token) - { - if (projectItems == null) - { - return Array.Empty(); - } - - var cts = new CancellationTokenSource(); - token.Register(() => cts.Cancel()); - var solutionProps = MSBuildListSplitter.GetNamedProperties(properties); - var projectFiles = projectItems.SelectMany(p => SolutionInfoFactory.GetProjects(p, solutionProps)).Distinct(); - var projects = new ConcurrentBag(); - var stop = Stopwatch.StartNew(); - - Parallel.ForEach(projectFiles, projectFile => - { - if (cts.Token.IsCancellationRequested) - { - return; - } - - try - { - projects.Add(Create(projectFile, policyDesignBuild)); - } - catch (Exception ex) - { - _logger.LogErrorFromException(ex); - cts.Cancel(); - } - }); - - stop.Stop(); - _logger.LogMessage(MessageImportance.Low, $"Finished design-time build in {stop.ElapsedMilliseconds}ms"); - return projects.ToArray(); - } - - public ProjectInfo Create(string path, bool policyDesignBuild) - { - var project = GetProject(path, ProjectCollection.GlobalProjectCollection, policyDesignBuild); - var instance = project.CreateProjectInstance(ProjectInstanceSettings.ImmutableWithFastItemLookup); - var projExtPath = instance.GetPropertyValue("MSBuildProjectExtensionsPath"); - - var targetFrameworks = instance.GetPropertyValue("TargetFrameworks"); - var targetFramework = instance.GetPropertyValue("TargetFramework"); - - var frameworks = new List(); - if (!string.IsNullOrEmpty(targetFrameworks) && string.IsNullOrEmpty(targetFramework)) - { - // multi targeting - foreach (var tfm in targetFrameworks.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) - { - project.SetGlobalProperty("TargetFramework", tfm); - var innerBuild = project.CreateProjectInstance(ProjectInstanceSettings.ImmutableWithFastItemLookup); - - var tfmInfo = new ProjectFrameworkInfo(NuGetFramework.Parse(tfm), GetDependencies(innerBuild)); - - frameworks.Add(tfmInfo); - } - - project.RemoveGlobalProperty("TargetFramework"); - } - else if (!string.IsNullOrEmpty(targetFramework)) - { - var tfmInfo = new ProjectFrameworkInfo(NuGetFramework.Parse(targetFramework), GetDependencies(instance)); - - frameworks.Add(tfmInfo); - } - - var projectDir = Path.GetDirectoryName(path); - - var tools = GetTools(instance).ToArray(); - - return new ProjectInfo(path, projExtPath, frameworks, tools); - } - - private static Project GetProject(string path, ProjectCollection projectCollection, bool policyDesignBuild) - { - var projects = projectCollection.GetLoadedProjects(path); - foreach (var proj in projects) - { - if (proj.GetPropertyValue("DesignTimeBuild") == "true") - { - return proj; - } - } - var xml = ProjectRootElement.Open(path, projectCollection); - var globalProps = new Dictionary() - { - ["DesignTimeBuild"] = "true", - }; - if (policyDesignBuild) - { - globalProps["PolicyDesignTimeBuild"] = "true"; - } - var project = new Project(xml, - globalProps, - toolsVersion: "15.0", - projectCollection: projectCollection) - { - IsBuildEnabled = false - }; - return project; - } - - private IReadOnlyDictionary GetDependencies(ProjectInstance project) - { - var references = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (var item in project.GetItems("PackageReference")) - { - bool.TryParse(item.GetMetadataValue("IsImplicitlyDefined"), out var isImplicit); - var noWarn = item.GetMetadataValue("NoWarn"); - IReadOnlyList noWarnItems = string.IsNullOrEmpty(noWarn) - ? Array.Empty() - : noWarn.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - - var info = new PackageReferenceInfo(item.EvaluatedInclude, item.GetMetadataValue("Version"), isImplicit, noWarnItems); - - if (references.ContainsKey(info.Id)) - { - _logger.LogKoreBuildWarning(project.ProjectFileLocation.File, KoreBuildErrors.DuplicatePackageReference, $"Found a duplicate PackageReference for {info.Id}. Restore results may be unpredictable."); - } - - references[info.Id] = info; - } - - return references; - } - - private static IEnumerable GetTools(ProjectInstance project) - { - return project.GetItems("DotNetCliToolReference").Select(item => - new DotNetCliReferenceInfo(item.EvaluatedInclude, item.GetMetadataValue("Version"))); - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfo.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfo.cs deleted file mode 100644 index d968438cb..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfo.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class SolutionInfo - { - public SolutionInfo(string fullPath, IReadOnlyList projects) - { - if (string.IsNullOrEmpty(fullPath)) - { - throw new ArgumentException(nameof(fullPath)); - } - - FullPath = fullPath; - Projects = projects ?? throw new ArgumentNullException(nameof(projects)); - } - - public string FullPath { get; } - - public IReadOnlyList Projects { get; } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfoFactory.cs b/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfoFactory.cs deleted file mode 100644 index 18d2a2550..000000000 --- a/modules/KoreBuild.Tasks/Internal/ProjectModel/SolutionInfoFactory.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.BuildTools; -using Microsoft.Build.Construction; -using Microsoft.Build.Framework; - -namespace KoreBuild.Tasks.ProjectModel -{ - internal class SolutionInfoFactory - { - public static SolutionInfo Create(string filePath, string configName) - { - var sln = SolutionFile.Parse(filePath); - - if (string.IsNullOrEmpty(configName)) - { - configName = sln.GetDefaultConfigurationName(); - } - - var projects = new List(); - - var config = sln.SolutionConfigurations.FirstOrDefault(c => c.ConfigurationName == configName); - if (config == null) - { - throw new InvalidOperationException($"A solution configuration by the name of '{configName}' was not found in '{filePath}'"); - } - - foreach (var project in sln.ProjectsInOrder - .Where(p => - p.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat // skips solution folders - && p.ProjectConfigurations.TryGetValue(config.FullName, out var projectConfig) - && projectConfig.IncludeInBuild)) - { - projects.Add(project.AbsolutePath.Replace('\\', '/')); - } - - return new SolutionInfo(filePath, projects.ToArray()); - } - - public static IEnumerable GetProjects(ITaskItem projectOrSolution, IDictionary solutionProperties) - { - var projectFilePath = projectOrSolution.ItemSpec.Replace('\\', '/'); - - if (Path.GetExtension(projectFilePath).Equals(".sln", StringComparison.OrdinalIgnoreCase)) - { - // prefer the AdditionalProperties metadata as this is what the MSBuild task will use when building solutions - var props = MSBuildListSplitter.GetNamedProperties(projectOrSolution.GetMetadata("AdditionalProperties")); - props.TryGetValue("Configuration", out var config); - - if (config == null) - { - solutionProperties.TryGetValue("Configuration", out config); - } - - var sln = Create(projectFilePath, config); - - foreach (var project in sln.Projects) - { - yield return project; - } - } - else - { - yield return Path.GetFullPath(projectFilePath); - } - } - } -} diff --git a/modules/KoreBuild.Tasks/Internal/SimplePackageInstaller.cs b/modules/KoreBuild.Tasks/Internal/SimplePackageInstaller.cs deleted file mode 100644 index 796c220a6..000000000 --- a/modules/KoreBuild.Tasks/Internal/SimplePackageInstaller.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Commands; -using NuGet.Common; -using NuGet.DependencyResolver; -using NuGet.LibraryModel; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Packaging.Signing; -using NuGet.Protocol.Core.Types; - -namespace KoreBuild.Tasks.Utilities -{ - internal class SimplePackageInstaller - { - private readonly string _packagesDirectory; - private readonly ILogger _logger; - private readonly SourceCacheContext _cacheContext; - private readonly int _maxDegreeOfConcurrency; - - public SimplePackageInstaller(string packageDir, SourceCacheContext cacheContext, bool disableParallel, ILogger logger) - { - _packagesDirectory = packageDir; - _cacheContext = cacheContext; - _logger = logger; - _maxDegreeOfConcurrency = disableParallel ? 1 : 16; - } - - public async Task InstallPackagesAsync(IEnumerable graphs, - HashSet allInstalledPackages, - CancellationToken token) - { - var packagesToInstall = graphs.SelectMany(g => g.Install.Where(match => allInstalledPackages.Add(match.Library))); - if (_maxDegreeOfConcurrency <= 1) - { - foreach (var match in packagesToInstall) - { - await InstallPackageAsync(match, token); - } - } - else - { - var bag = new ConcurrentBag(packagesToInstall); - var tasks = Enumerable.Range(0, _maxDegreeOfConcurrency) - .Select(async _ => - { - while (bag.TryTake(out RemoteMatch match)) - { - await InstallPackageAsync(match, token); - } - }); - await Task.WhenAll(tasks); - } - } - - private async Task InstallPackageAsync(RemoteMatch installItem, CancellationToken token) - { - var packageIdentity = new PackageIdentity(installItem.Library.Name, installItem.Library.Version); - - var verificationProviders = SignatureVerificationProviderFactory.GetSignatureVerificationProviders(); - var signedPackageVerifier = new PackageSignatureVerifier(verificationProviders); - - var versionFolderPathResolver = new VersionFolderPathResolver(_packagesDirectory); - var packageExtractionContext = new PackageExtractionContext( - PackageSaveMode.Defaultv3, - XmlDocFileSaveMode.None, - _logger, - signedPackageVerifier, - SignedPackageVerifierSettings.GetDefault()); - - using (var packageDependency = await installItem.Provider.GetPackageDownloaderAsync( - packageIdentity, - _cacheContext, - _logger, - token)) - { - await PackageExtractor.InstallFromSourceAsync( - packageIdentity, - packageDependency, - versionFolderPathResolver, - packageExtractionContext, - token); - } - } - } -} diff --git a/modules/KoreBuild.Tasks/KoreBuild.Tasks.csproj b/modules/KoreBuild.Tasks/KoreBuild.Tasks.csproj index 0c42f0032..12ff8c23f 100644 --- a/modules/KoreBuild.Tasks/KoreBuild.Tasks.csproj +++ b/modules/KoreBuild.Tasks/KoreBuild.Tasks.csproj @@ -12,21 +12,17 @@ - - - - diff --git a/tools/KoreBuildSettings.cs b/modules/KoreBuild.Tasks/KoreBuildSettings.cs similarity index 100% rename from tools/KoreBuildSettings.cs rename to modules/KoreBuild.Tasks/KoreBuildSettings.cs diff --git a/modules/KoreBuild.Tasks/PackNuSpec.cs b/modules/KoreBuild.Tasks/PackNuSpec.cs deleted file mode 100644 index f711a4fbb..000000000 --- a/modules/KoreBuild.Tasks/PackNuSpec.cs +++ /dev/null @@ -1,250 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.BuildTools; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Versioning; - -namespace KoreBuild.Tasks -{ - /// - /// Generates a nupkg from a nuspec file - /// - public class PackNuSpec : Microsoft.Build.Utilities.Task - { - /// - /// The path the nuspec file. - /// - [Required] - public string NuspecPath { get; set; } - - /// - /// Output nupkg is placed in folder + '$(id).$(version).nupkg'. - /// Either this or must be specified. - /// - public string DestinationFolder { get; set; } - - /// - /// The output path for the nupkg. - /// Either this or must be specified. - /// - public string OutputPath { get; set; } - - /// - /// The base path to use for any relative paths in the <files%gt; section of nuspec. - /// Defaults to the nuspec folder. - /// - public string BasePath { get; set; } - - /// - /// Dependencies to add to the metadata>dependencies section of the spec. - /// Metadata 'TargetFramework' can be specified to further put dependencies into >group[targetFramework] - /// - public ITaskItem[] Dependencies { get; set; } - - /// - /// Files to add to the package. Must specify the PackagePath metadata. - /// - public ITaskItem[] PackageFiles { get; set; } - - /// - /// Subsitution in the nuspec via $key$. - /// - public string[] Properties { get; set; } - - /// - /// Pack empty directories. - /// - public bool IncludeEmptyDirectories { get; set; } = false; - - /// - /// Overwrite the destination file if it exists. - /// - public bool Overwrite { get; set; } = false; - - /// - /// The nupkg files created - /// - [Output] - public ITaskItem[] Packages { get; set; } - - public override bool Execute() - { - if (!File.Exists(NuspecPath)) - { - Log.LogError("Nuspec does not exist: " + NuspecPath); - return false; - } - - var packageBasePath = string.IsNullOrEmpty(BasePath) - ? Path.GetDirectoryName(NuspecPath) - : BasePath; - - if (!Directory.Exists(packageBasePath)) - { - Log.LogError("Base path does not exist: " + packageBasePath); - return false; - } - - if (!(string.IsNullOrEmpty(DestinationFolder) ^ string.IsNullOrEmpty(OutputPath))) - { - Log.LogError("Either DestinationFolder and OutputPath must be specified, but only not both."); - return false; - } - - var properties = MSBuildListSplitter.GetNamedProperties(Properties); - - string PropertyProvider(string name) - { - if (properties.TryGetValue(name, out var value)) - { - return value; - } - Log.LogError("Undefined property: " + name); - return null; - } - - PackageBuilder packageBuilder; - try - { - Log.LogMessage($"Loading nuspec {NuspecPath}"); - - using (var file = File.OpenRead(NuspecPath)) - { - var manifest = Manifest.ReadFrom(file, PropertyProvider, validateSchema: false); - if (!manifest.HasFilesNode) - { - // Warn about this overly permissive default in nuspec. - Log.LogKoreBuildWarning(KoreBuildErrors.NuspecMissingFilesNode, - "The nuspec file is missing the nodes. This causes all files in NuspecBase to be included in the package. " + - @"Add an empty `` node to prevent this behavior. Add ` ` to the nuspec to suppress this warning."); - } - } - - packageBuilder = new PackageBuilder(NuspecPath, packageBasePath, PropertyProvider, IncludeEmptyDirectories); - } - catch (InvalidDataException ex) - { - Log.LogKoreBuildError(NuspecPath, KoreBuildErrors.InvalidNuspecFile, ex.Message); - return false; - } - - if (Dependencies != null) - { - AddDependencies(packageBuilder); - } - - if (PackageFiles != null) - { - AddFiles(packageBuilder); - } - - if (Log.HasLoggedErrors) - { - return false; - } - - var dest = !string.IsNullOrEmpty(OutputPath) - ? OutputPath - : Path.Combine(DestinationFolder, $"{packageBuilder.Id}.{packageBuilder.Version}.nupkg"); - - // normalize path - dest = Path.GetFullPath(dest); - - Directory.CreateDirectory(Path.GetDirectoryName(dest)); - - if (!Overwrite && File.Exists(dest)) - { - Log.LogError($"File path '{dest}' already exists. Set Overwrite=true to overwrite the destination nupkg file."); - return false; - } - - if (packageBuilder.Files != null) - { - foreach (var file in packageBuilder.Files) - { - if (file is PhysicalPackageFile p) - { - Log.LogMessage($"Packing {p.SourcePath} => {p.Path}"); - } - else - { - Log.LogMessage($"Packing {file.Path}"); - } - } - } - - using (var stream = File.Create(dest)) - { - packageBuilder.Save(stream); - } - - Log.LogMessage(MessageImportance.High, $"Created package {dest}"); - Packages = new[] { new TaskItem(dest) }; - - return true; - } - - private void AddFiles(PackageBuilder builder) - { - foreach (var file in PackageFiles) - { - var packagePath = file.GetMetadata("PackagePath"); - var fileName = Path.GetFileName(packagePath); - if (string.IsNullOrEmpty(fileName)) - { - Log.LogKoreBuildError(KoreBuildErrors.InvalidPackagePathMetadata, - "The PackagePath metadata value on {0} is invalid. PackagePath must be set to the exact file path within the nuget package."); - continue; - } - - builder.Files.Add(new PhysicalPackageFile - { - SourcePath = file.ItemSpec, - TargetPath = packagePath, - }); - } - } - - private void AddDependencies(PackageBuilder builder) - { - var packageRequest = Dependencies.Select(d => - { - NuGetFramework tfm = NuGetFramework.AnyFramework; - if (!string.IsNullOrEmpty(d.GetMetadata("TargetFramework"))) - { - tfm = NuGetFramework.Parse(d.GetMetadata("TargetFramework")); - } - - if (string.IsNullOrEmpty(d.GetMetadata("Version"))) - { - Log.LogError($"Dependency {d.ItemSpec} is missing expected metdata: Version"); - } - - return new - { - tfm, - dependency = new PackageDependency(d.ItemSpec, - VersionRange.Parse(d.GetMetadata("Version")), - d.GetMetadata("IncludeAssets").Split(';').Select(s => s.Trim()).ToArray(), - d.GetMetadata("ExcludeAssets").Split(';').Select(s => s.Trim()).ToArray()) - }; - }); - - foreach (var group in packageRequest.GroupBy(g => g.tfm)) - { - var existingPackages = builder.DependencyGroups.FirstOrDefault(g => g.TargetFramework == group.Key)?.Packages - ?? Enumerable.Empty(); - - var depGroup = new PackageDependencyGroup(group.Key, existingPackages.Concat(group.Select(d => d.dependency))); - builder.DependencyGroups.Add(depGroup); - } - } - } -} diff --git a/modules/KoreBuild.Tasks/PushNuGetPackages.cs b/modules/KoreBuild.Tasks/PushNuGetPackages.cs deleted file mode 100644 index ae564dc98..000000000 --- a/modules/KoreBuild.Tasks/PushNuGetPackages.cs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Build.Framework; -using NuGet.Common; -using NuGet.Packaging; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using KoreBuild.Tasks.Internal; - -namespace KoreBuild.Tasks -{ - public class PushNuGetPackages : Microsoft.Build.Utilities.Task, ICancelableTask - { - private const int _maxRetryCount = 5; - private const int _maxParallelPackagePushes = 4; - - private ConcurrentBag _packages; - private readonly CancellationTokenSource _packagePushCancellationTokenSource = new CancellationTokenSource(); - - [Required] - public ITaskItem[] Packages { get; set; } - - [Required] - public string Feed { get; set; } - - // not be required if pushing to the filesystem - public string ApiKey { get; set; } - - public int TimeoutSeconds { get; set; } = 300; - - public void Cancel() - { - _packagePushCancellationTokenSource.Cancel(); - } - - public override bool Execute() - { - if (Packages.Length == 0) - { - Log.LogWarning("No package files were found to be published."); - return true; - } - - if (string.IsNullOrEmpty(Feed)) - { - Log.LogError("Feed must not be null or empty."); - return false; - } - - var packages = Packages - .Select(fileInfo => - { - using (var fileStream = File.OpenRead(fileInfo.ItemSpec)) - using (var reader = new PackageArchiveReader(fileStream)) - { - return new PackageInfo - { - Identity = reader.GetIdentity(), - PackagePath = fileInfo.ItemSpec - }; - } - }); - - _packages = new ConcurrentBag(packages); - - Log.LogMessage(MessageImportance.High, "Attempting to push {0} package(s) to {1}", Packages.Length, Feed); - try - { - PublishToFeedAsync().GetAwaiter().GetResult(); - Log.LogMessage(MessageImportance.High, "Successfully pushed {0} package(s) to {1}", Packages.Length, Feed); - return true; - } - catch (Exception ex) - { - Log.LogErrorFromException(ex, showStackTrace: true); - return false; - } - } - - private async Task PublishToFeedAsync() - { - Log.LogMessage("Publishing packages to feed: {0}", Feed); - - var sourceRepository = Repository.Factory.GetCoreV3(Feed, FeedType.HttpV3); - var packageUpdateResource = await sourceRepository.GetResourceAsync(); - - var tasks = new Task[_maxParallelPackagePushes]; - for (var i = 0; i < tasks.Length; i++) - { - tasks[i] = PushPackagesAsync(packageUpdateResource); - } - - await Task.WhenAll(tasks); - } - - private async Task PushPackagesAsync(PackageUpdateResource packageUpdateResource) - { - while (_packages.TryTake(out var package)) - { - await PushPackageAsync(packageUpdateResource, package); - } - } - - private async Task PushPackageAsync(PackageUpdateResource packageUpdateResource, PackageInfo package) - { - for (var attempt = 1; attempt <= _maxRetryCount; attempt++) - { - // Fail fast if a parallel push operation has already failed - _packagePushCancellationTokenSource.Token.ThrowIfCancellationRequested(); - - Log.LogMessage($"Attempting to publish package {package.Identity} (Attempt: {attempt})"); - - try - { - await packageUpdateResource.Push( - package.PackagePath, - symbolSource: null, - timeoutInSecond: TimeoutSeconds, - disableBuffering: false, - getApiKey: _ => ApiKey, - getSymbolApiKey: _ => null, - noServiceEndpoint: false, - log: NullLogger.Instance); - - Log.LogMessage(MessageImportance.High, $"Published package {package.Identity}"); - - return; - } - catch (Exception ex) when (attempt < _maxRetryCount) // allow exception to be thrown at the last attempt - { - Log.LogMessage( - MessageImportance.High, - $"Attempt {attempt} failed to publish package {package.Identity}." + - Environment.NewLine + - ex + - Environment.NewLine + - "Retrying..."); - } - catch - { - _packagePushCancellationTokenSource.Cancel(); - throw; - } - } - } - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/AssembliesFile.cs b/modules/KoreBuild.Tasks/SkipStrongName/AssembliesFile.cs deleted file mode 100644 index 9fb2343be..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/AssembliesFile.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Xml.Linq; - -namespace KoreBuild.Tasks.SkipStrongNames -{ - internal static class AssembliesFile - { - public static AssemblySpecification[] Read(string path) - { - XElement assembliesElement = XElement.Load(path); - - if (assembliesElement.Name != "assemblies") - { - throw new InvalidOperationException("The name of the root element must be assemblies."); - } - - XAttribute defaultPublicKeyTokenAttribute = assembliesElement.Attribute("defaultPublicKeyToken"); - - string defaultPublicKeyToken; - - if (defaultPublicKeyTokenAttribute != null) - { - defaultPublicKeyToken = defaultPublicKeyTokenAttribute.Value; - } - else - { - defaultPublicKeyToken = null; - } - - List specifications = new List(); - - foreach (XElement assembly in assembliesElement.Elements("assembly")) - { - XAttribute nameAttribute = assembly.Attribute("name"); - - if (nameAttribute == null) - { - throw new InvalidOperationException("An assembly element must have a name attribute."); - } - - XAttribute publicKeyTokenAttribute = assembly.Attribute("publicKeyToken"); - string publicKeyToken; - - if (publicKeyTokenAttribute != null) - { - publicKeyToken = publicKeyTokenAttribute.Value; - } - else - { - publicKeyToken = defaultPublicKeyToken; - } - - if (publicKeyToken == null) - { - throw new InvalidOperationException("An assembly element must have a publicKeyToken attribute, " + - "or the assemblies element must have a defaultPublicKeyToken attribute."); - } - - specifications.Add(new AssemblySpecification - { - Name = nameAttribute.Value, - PublicKeyToken = publicKeyToken - }); - } - - if (specifications.Count == 0) - { - throw new InvalidOperationException( - "The assemblies element must contain at least one assembly element."); - } - - return specifications.ToArray(); - } - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/AssemblySpecification.cs b/modules/KoreBuild.Tasks/SkipStrongName/AssemblySpecification.cs deleted file mode 100644 index 5f6798254..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/AssemblySpecification.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -namespace KoreBuild.Tasks.SkipStrongNames -{ - internal class AssemblySpecification - { - public string Name { get; set; } - - public string PublicKeyToken { get; set; } - - public override string ToString() - { - return Name + "," + PublicKeyToken; - } - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/RegistrySection.cs b/modules/KoreBuild.Tasks/SkipStrongName/RegistrySection.cs deleted file mode 100644 index 2999ae1d0..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/RegistrySection.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -namespace KoreBuild.Tasks.SkipStrongNames -{ - public enum RegistrySection - { - Native, - Windows32OnWindows64 - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/Status.cs b/modules/KoreBuild.Tasks/SkipStrongName/Status.cs deleted file mode 100644 index 2f37811fe..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/Status.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -namespace KoreBuild.Tasks.SkipStrongNames -{ - public enum Status - { - Disabled, - Enabled, - PartiallyEnabled, - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/StrongNameConfiguration.cs b/modules/KoreBuild.Tasks/SkipStrongName/StrongNameConfiguration.cs deleted file mode 100644 index 80dedffc5..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/StrongNameConfiguration.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace KoreBuild.Tasks.SkipStrongNames -{ - internal class StrongNameConfiguration - { - private readonly Dictionary> _strongNameExclusions; - private readonly AssemblySpecification[] _assemblies; - - public StrongNameConfiguration(AssemblySpecification[] specifications) - { - if (specifications != null) - { - _assemblies = specifications.OrderBy(s => s.Name).ToArray(); - } - else - { - _assemblies = null; - } - - FilteredAssemblySpecifications = new Dictionary(); - _strongNameExclusions = new Dictionary>(); - - foreach (RegistrySection section in WindowsRegistry.Sections) - { - HashSet sectionExclusions = WindowsRegistry.LoadStrongNameExclusions(section); - string[] sectionFilteredAssemblies = FilterAssemblySpecifications(_assemblies, sectionExclusions); - - FilteredAssemblySpecifications.Add(section, sectionFilteredAssemblies); - _strongNameExclusions.Add(section, sectionExclusions); - } - } - - public Dictionary FilteredAssemblySpecifications { get; private set; } - - public Status Status - { - get - { - bool allFound = true; - bool anyFound = false; - - foreach (RegistrySection section in WindowsRegistry.Sections) - { - string[] sectionFilteredAssemblies = FilteredAssemblySpecifications[section]; - HashSet sectionExclusions = _strongNameExclusions[section]; - - foreach (string assemblySpecification in sectionFilteredAssemblies) - { - bool found = sectionExclusions.Contains(assemblySpecification); - allFound = allFound && found; - anyFound = anyFound || found; - - if (!allFound && anyFound) - { - break; - } - } - } - - if (allFound) - { - return Status.Enabled; - } - else if (anyFound) - { - return Status.PartiallyEnabled; - } - else - { - return Status.Disabled; - } - } - } - - private string[] FilterAssemblySpecifications(AssemblySpecification[] assemblies, HashSet exclusions) - { - if (assemblies == null || assemblies.Length == 0) - { - return new string[0]; - } - - // Determine whether strong name verification is disabled globally (with a "*,*" entry). - if (exclusions.Contains("*,*")) - { - return new string[0]; - } - - // Get a list of the public key tokens that are globally excluded (with a "*,PublicKeyToken" entry) - HashSet globallyExcludedPublicKeyTokens = new HashSet(StringComparer.InvariantCultureIgnoreCase); - - foreach (var publicKeyToken in assemblies.Select(a => a.PublicKeyToken.ToUpperInvariant()).Distinct()) - { - if (exclusions.Contains("*," + publicKeyToken)) - { - globallyExcludedPublicKeyTokens.Add(publicKeyToken); - } - } - - // Create specifications for the list of the assemblies not covered by a global exclusion - return (from element in assemblies - where !globallyExcludedPublicKeyTokens.Contains(element.PublicKeyToken) - select element.ToString()).ToArray(); - } - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongName/WindowsRegistry.cs b/modules/KoreBuild.Tasks/SkipStrongName/WindowsRegistry.cs deleted file mode 100644 index 6e7a5aae8..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongName/WindowsRegistry.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.Win32; - -namespace KoreBuild.Tasks.SkipStrongNames -{ - internal static class WindowsRegistry - { - private const string SoftwareNativeKeyName = "SOFTWARE"; - private const string SoftwareWowKeyName = @"SOFTWARE\Wow6432Node"; - private const string VerificationSubKeyName = @"Microsoft\StrongName\Verification"; - - private static readonly Lazy softwareWowExists = new Lazy(() => CheckRegistryKeyExists(SoftwareWowKeyName)); - - public static IEnumerable Sections - { - get - { - yield return RegistrySection.Native; - - if (softwareWowExists.Value) - { - yield return RegistrySection.Windows32OnWindows64; - } - } - } - - public static RegistryKey CreateWritableVerificationRegistryKey(RegistrySection section) - { - return CreateWriteableRegistryKey(GetBaseKeyName(section), VerificationSubKeyName); - } - - public static HashSet LoadStrongNameExclusions(RegistrySection section) - { - HashSet results = new HashSet(StringComparer.OrdinalIgnoreCase); - - using (RegistryKey key = OpenReadOnlyVerificationRegistryKey(section)) - { - if (key != null) - { - foreach (var subKey in key.GetSubKeyNames()) - { - results.Add(subKey); - } - } - } - - return results; - } - - private static bool CheckRegistryKeyExists(string name) - { - using (RegistryKey key = OpenReadOnlyRegistryKey(name)) - { - return key != null; - } - } - - private static RegistryKey CreateWriteableRegistryKey(string baseKeyName, string subKeyName) - { - List keysToDispose = new List(); - - try - { - RegistryKey currentKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(baseKeyName, writable: true); - - if (currentKey == null) - { - return null; - } - - string[] subKeyParts = subKeyName.Split('\\'); - - foreach (string subKeyPart in subKeyParts) - { - keysToDispose.Add(currentKey); - currentKey = currentKey.CreateSubKey(subKeyPart); - } - - return currentKey; - } - finally - { - foreach (RegistryKey key in keysToDispose) - { - key.Dispose(); - } - } - } - - private static string GetBaseKeyName(RegistrySection section) - { - switch (section) - { - case RegistrySection.Windows32OnWindows64: - return SoftwareWowKeyName; - case RegistrySection.Native: - default: - return SoftwareNativeKeyName; - } - } - - private static RegistryKey OpenReadOnlyRegistryKey(string name) - { - return Microsoft.Win32.Registry.LocalMachine.OpenSubKey(name); - } - - private static RegistryKey OpenReadOnlyVerificationRegistryKey(RegistrySection section) - { - string keyName = GetBaseKeyName(section) + '\\' + VerificationSubKeyName; - return OpenReadOnlyRegistryKey(keyName); - } - } -} diff --git a/modules/KoreBuild.Tasks/SkipStrongNames.xml b/modules/KoreBuild.Tasks/SkipStrongNames.xml deleted file mode 100644 index 3457d438e..000000000 --- a/modules/KoreBuild.Tasks/SkipStrongNames.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/modules/KoreBuild.Tasks/UpgradeDependencies.cs b/modules/KoreBuild.Tasks/UpgradeDependencies.cs deleted file mode 100644 index 4e5ca9006..000000000 --- a/modules/KoreBuild.Tasks/UpgradeDependencies.cs +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using System.Xml; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; -using Microsoft.Build.Framework; -using NuGet.Build; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; -using NuGet.Versioning; - -namespace KoreBuild.Tasks -{ - /// - /// Uses a remote package to update the version variables in the local dependencies.props file - /// - public class UpgradeDependencies : Microsoft.Build.Utilities.Task, ICancelableTask - { - private CancellationTokenSource _cts = new CancellationTokenSource(); - - /// - /// The lineup package ID of the nupkg that contains the master dependencies.props files that will be used to upgrade versions - /// - [Required] - public string LineupPackageId { get; set; } - - /// - /// The version of the lineup package. If empty, this will attempt to pull the latest - /// - public string LineupPackageVersion { get; set; } - - /// - /// The dependencies.props file to use versions from - /// - public string LineupDependenciesFile { get; set; } - - /// - /// The NuGet feed containing the lineup package - /// - [Required] - public string LineupPackageRestoreSource { get; set; } - - /// - /// The dependencies.props file to update - /// - [Required] - public string DependenciesFile { get; set; } - - public void Cancel() - { - _cts.Cancel(); - } - - public override bool Execute() - { - return ExecuteAsync().GetAwaiter().GetResult(); - } - - public async Task ExecuteAsync() - { - if (!DependencyVersionsFile.TryLoad(DependenciesFile, out var localVersionsFile)) - { - Log.LogError($"Could not load file from {DependenciesFile}"); - return false; - } - - if (!localVersionsFile.HasVersionsPropertyGroup) - { - Log.LogKoreBuildWarning(KoreBuildErrors.PackageRefPropertyGroupNotFound, $"No PropertyGroup with Label=\"{DependencyVersionsFile.PackageVersionsLabel}\" could be found in {DependenciesFile}"); - } - - if (localVersionsFile.VersionVariables.Count == 0) - { - Log.LogMessage(MessageImportance.High, $"No version variables could be found in {DependenciesFile}"); - return true; - } - - - var tmpNupkgPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - var logger = new MSBuildLogger(Log); - - try - { - var remoteDepsVersionFile = await TryDownloadLineupDepsFile() ?? await TryDownloadLineupPackage(logger, tmpNupkgPath); - - if (remoteDepsVersionFile == null) - { - return false; - } - - var updateCount = UpdateDependencies(localVersionsFile, remoteDepsVersionFile); - - if (updateCount > 0) - { - Log.LogMessage($"Finished updating {updateCount} version variables in {DependenciesFile}"); - localVersionsFile.Save(DependenciesFile); - } - else - { - Log.LogMessage($"Versions in {DependenciesFile} are already up to date"); - } - - return !Log.HasLoggedErrors; - } - finally - { - if (File.Exists(tmpNupkgPath)) - { - File.Delete(tmpNupkgPath); - } - } - } - - private async Task TryDownloadLineupDepsFile() - { - if (string.IsNullOrEmpty(LineupDependenciesFile)) - { - return null; - } - - var path = LineupDependenciesFile; - string text; - if (path.StartsWith("http")) - { - using (var client = new HttpClient()) - { - text = await client.GetStringAsync(path); - } - } - else - { - text = File.ReadAllText(path); - } - - - using (var stringReader = new StringReader(text)) - using (var reader = new XmlTextReader(stringReader)) - { - var project = new Project(ProjectRootElement.Create(reader)); - return DependencyVersionsFile.LoadFromProject(project); - } - } - - private async Task TryDownloadLineupPackage(MSBuildLogger logger, string tmpNupkgPath) - { - VersionRange versionRange; - - if (string.IsNullOrEmpty(LineupPackageVersion)) - { - versionRange = VersionRange.AllFloating; - } - else if (!VersionRange.TryParse(LineupPackageVersion, out versionRange)) - { - Log.LogError($"{LineupPackageVersion} is not a valid NuGet package version"); - return null; - } - - var packageVersion = await GetPackageVersion(versionRange); - if (packageVersion == null) - { - Log.LogError($"Could not find a version of {LineupPackageId} in the version range {versionRange}."); - return null; - } - - var packageId = new PackageIdentity(LineupPackageId, packageVersion); - - var request = new PackageDownloadRequest - { - Identity = packageId, - OutputPath = tmpNupkgPath, - Sources = new[] { LineupPackageRestoreSource }, - }; - - var result = await new PackageDownloader(logger).DownloadPackagesAsync(new[] { request }, TimeSpan.FromSeconds(60), _cts.Token); - - if (!result) - { - Log.LogError("Could not download the lineup package"); - return null; - } - - using (var nupkgReader = new PackageArchiveReader(tmpNupkgPath)) - using (var stream = nupkgReader.GetStream("build/dependencies.props")) - using (var reader = new XmlTextReader(stream)) - { - var projectRoot = ProjectRootElement.Create(reader); - return DependencyVersionsFile.Load(projectRoot); - } - } - - private int UpdateDependencies(DependencyVersionsFile localVersionsFile, DependencyVersionsFile remoteDepsVersionFile) - { - var updateCount = 0; - foreach (var localVariable in localVersionsFile.VersionVariables.Values.Where(v => !v.IsReadOnly)) - { - string remoteVariableVersion; - // special case any package bundled in KoreBuild - if (!string.IsNullOrEmpty(KoreBuildVersion.Current) && localVariable.Name == "InternalAspNetCoreSdkPackageVersion") - { - remoteVariableVersion = KoreBuildVersion.Current; - Log.LogMessage(MessageImportance.Low, "Setting InternalAspNetCoreSdkPackageVersion to the current version of KoreBuild"); - } - else - { - if (remoteDepsVersionFile.VersionVariables.TryGetValue(localVariable.Name, out var remoteVariable)) - { - remoteVariableVersion = remoteVariable.Version; - } - else - { - Log.LogKoreBuildWarning( - DependenciesFile, KoreBuildErrors.PackageVersionNotFoundInLineup, - $"A new version variable for {localVariable.Name} could not be found in {LineupPackageId}. This might be an unsupported external dependency."); - continue; - } - } - - - if (remoteVariableVersion != localVariable.Version) - { - updateCount++; - localVersionsFile.Update(localVariable.Name, remoteVariableVersion); - } - } - - return updateCount; - } - - private async Task GetPackageVersion(VersionRange range) - { - if (!range.IsFloating) - { - return range.MinVersion; - } - - using (var cacheContext = new SourceCacheContext()) - { - var log = new MSBuildLogger(Log); - var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null); - var sourceProvider = new CachingSourceProvider(new PackageSourceProvider(defaultSettings)); - - var repo = sourceProvider.CreateRepository(new PackageSource(LineupPackageRestoreSource)); - - var metadata = await repo.GetResourceAsync(); - if (!await metadata.Exists(LineupPackageId, cacheContext, log, _cts.Token)) - { - Log.LogError($"Package {LineupPackageId} is not available on '{repo}'"); - return null; - } - - try - { - var versions = await metadata.GetVersions(LineupPackageId, includePrerelease: true, includeUnlisted: false, sourceCacheContext: cacheContext, log: log, token: _cts.Token); - - return range.FindBestMatch(versions); - } - catch (Exception ex) - { - Log.LogError($"Unexpected error while fetching versions from {repo.PackageSource.Source}: " + ex.Message); - return null; - } - } - } - } -} diff --git a/modules/KoreBuild.Tasks/Utilities/DependencyVersionsFile.cs b/modules/KoreBuild.Tasks/Utilities/DependencyVersionsFile.cs deleted file mode 100644 index 2b50a02b1..000000000 --- a/modules/KoreBuild.Tasks/Utilities/DependencyVersionsFile.cs +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; - -namespace KoreBuild.Tasks.Utilities -{ - public class DependencyVersionsFile - { - public const string PackageVersionsLabel = "Package Versions"; - - public const string AutoPackageVersionsLabel = "Package Versions: Auto"; - public const string PinnedPackageVersionsLabel = "Package Versions: Pinned"; - - private readonly Dictionary _versionVariables - = new Dictionary(StringComparer.OrdinalIgnoreCase); - - //private readonly SortedDictionary _versionElements - // = new SortedDictionary(StringComparer.OrdinalIgnoreCase); - - private readonly ProjectRootElement _document; - private ProjectPropertyGroupElement _autoPackageVersions; - private ProjectPropertyGroupElement _pinnedPackageVersions; - - private DependencyVersionsFile(ProjectRootElement xDocument) - { - _document = xDocument; - } - - public static string GetVariableName(string packageId) - { - var sb = new StringBuilder(); - var first = true; - foreach (var ch in packageId) - { - if (!char.IsLetterOrDigit(ch)) - { - first = true; - continue; - } - - if (first) - { - first = false; - sb.Append(char.ToUpperInvariant(ch)); - } - else - { - sb.Append(ch); - } - } - sb.Append("PackageVersion"); - return sb.ToString(); - } - - - public static DependencyVersionsFile Create(bool addOverrideImport, string[] additionalImports = null) - { - var projectRoot = ProjectRootElement.Create(NewProjectFileOptions.None); - - projectRoot.AddPropertyGroup().AddProperty("MSBuildAllProjects", "$(MSBuildAllProjects);$(MSBuildThisFileFullPath)"); - - var autoPackageVersions = projectRoot.AddPropertyGroup(); - autoPackageVersions.Label = AutoPackageVersionsLabel; - - if (additionalImports != null) - { - foreach (var item in additionalImports) - { - var import = projectRoot.AddImport(item); - import.Condition = $"Exists('{item}')"; - } - } - - if (addOverrideImport) - { - var import = projectRoot.AddImport("$(DotNetPackageVersionPropsPath)"); - import.Condition = " '$(DotNetPackageVersionPropsPath)' != '' "; - } - - var pinnedPackageVersions = projectRoot.AddPropertyGroup(); - pinnedPackageVersions.Label = PinnedPackageVersionsLabel; - - return new DependencyVersionsFile(projectRoot) - { - _autoPackageVersions = autoPackageVersions, - _pinnedPackageVersions = pinnedPackageVersions, - }; - } - - public static bool TryLoad(string sourceFile, out DependencyVersionsFile file) - { - try - { - file = Load(sourceFile); - return true; - } - catch - { - file = null; - return false; - } - } - - public static DependencyVersionsFile Load(string sourceFile) - { - var project = ProjectRootElement.Open(sourceFile, ProjectCollection.GlobalProjectCollection, preserveFormatting: true); - return Load(project); - } - - public static DependencyVersionsFile Load(ProjectRootElement document) - { - var file = new DependencyVersionsFile(document); - - var propGroups = file._document.PropertyGroups; - - var listPropertyGroups = new List(); - - foreach (var propGroup in propGroups) - { - var attr = propGroup.Label; - if (attr != null && attr.StartsWith(PackageVersionsLabel, StringComparison.OrdinalIgnoreCase)) - { - file.HasVersionsPropertyGroup = true; - listPropertyGroups.Add(propGroup); - } - } - - foreach (var group in listPropertyGroups) - { - var isReadOnly = string.Equals(group.Label, PinnedPackageVersionsLabel, StringComparison.OrdinalIgnoreCase); - if (isReadOnly) - { - file._pinnedPackageVersions = group; - } - else - { - file._autoPackageVersions = group; - } - - foreach (var child in group.Properties) - { - var variable = new PackageVersionVariable(child, isReadOnly); - file._versionVariables[variable.Name] = variable; - } - } - - file.EnsureGroupsCreated(); - return file; - } - - private void EnsureGroupsCreated() - { - if (_autoPackageVersions == null) - { - _autoPackageVersions = _document.AddPropertyGroup(); - _autoPackageVersions.Label = AutoPackageVersionsLabel; - } - - if (_pinnedPackageVersions == null) - { - _pinnedPackageVersions = _document.AddPropertyGroup(); - _pinnedPackageVersions.Label = PinnedPackageVersionsLabel; - } - } - - public static DependencyVersionsFile LoadFromProject(Project project) - { - var file = new DependencyVersionsFile(ProjectRootElement.Create(NewProjectFileOptions.None)); - - foreach (var property in project.AllEvaluatedProperties.Where(p => p.Xml != null)) - { - var group = (ProjectPropertyGroupElement)property.Xml.Parent; - var isReadOnly = string.Equals(group.Label, PinnedPackageVersionsLabel, StringComparison.OrdinalIgnoreCase); - - var variable = new PackageVersionVariable(property.Xml, property.EvaluatedValue?.Trim(), isReadOnly); - file._versionVariables[property.Name] = variable; - } - - file.EnsureGroupsCreated(); - - return file; - } - - public bool HasVersionsPropertyGroup { get; private set; } - - // copying is required so calling .Set while iterating on this doesn't raise an InvalidOperationException - public IReadOnlyDictionary VersionVariables - => new Dictionary(_versionVariables, StringComparer.OrdinalIgnoreCase); - - public PackageVersionVariable Update(string variableName, string version) - { - if (!_versionVariables.TryGetValue(variableName, out var variable)) - { - var element = _document.CreatePropertyElement(variableName); - variable = new PackageVersionVariable(element, version, isReadOnly: false); - _versionVariables[variableName] = variable; - variable.AddToGroup(_autoPackageVersions); - } - - variable.UpdateVersion(version); - return variable; - } - - public PackageVersionVariable AddPinnedVariable(string variableName, string version) - { - if (_versionVariables.ContainsKey(variableName)) - { - throw new InvalidOperationException("Key already exists: " + variableName); - } - - var element = _document.CreatePropertyElement(variableName); - var variable = new PackageVersionVariable(element, version, isReadOnly: true); - _versionVariables.Add(variableName, variable); - variable.AddToGroup(_pinnedPackageVersions); - return variable; - } - - public void Save(string filePath) - { - _autoPackageVersions.RemoveAllChildren(); - foreach (var item in _versionVariables.Values.Where(v => !v.IsReadOnly).OrderBy(v => v.Name)) - { - item.AddToGroup(_autoPackageVersions); - } - - _document.Save(filePath, Encoding.UTF8); - } - } -} diff --git a/modules/KoreBuild.Tasks/Utilities/PackageDownloadRequest.cs b/modules/KoreBuild.Tasks/Utilities/PackageDownloadRequest.cs deleted file mode 100644 index 40aeef381..000000000 --- a/modules/KoreBuild.Tasks/Utilities/PackageDownloadRequest.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using NuGet.Packaging.Core; - -namespace KoreBuild.Tasks.Utilities -{ - public class PackageDownloadRequest - { - public PackageIdentity Identity { get; set; } - public string OutputPath { get; set; } - public IReadOnlyList Sources { get; set; } - } -} diff --git a/modules/KoreBuild.Tasks/Utilities/PackageDownloader.cs b/modules/KoreBuild.Tasks/Utilities/PackageDownloader.cs deleted file mode 100644 index 9d5a9ac32..000000000 --- a/modules/KoreBuild.Tasks/Utilities/PackageDownloader.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using NuGet.Commands; -using NuGet.Configuration; -using NuGet.Packaging.Core; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; - -namespace KoreBuild.Tasks.Utilities -{ - public class PackageDownloader - { - private static readonly Task FalseTask = Task.FromResult(false); - private readonly NuGet.Common.ILogger logger; - - public PackageDownloader(NuGet.Common.ILogger logger) - { - this.logger = logger; - } - - public async Task DownloadPackagesAsync(ICollection requests, TimeSpan timeout, CancellationToken cancellationToken) - { - logger.LogMinimal($"Downloading {requests.Count} package(s)"); - - var cts = new CancellationTokenSource(timeout); - cancellationToken.Register(() => cts.Cancel()); - - using (var cacheContext = new SourceCacheContext()) - using (var throttle = new SemaphoreSlim(8)) - { - var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null); - var sourceProvider = new CachingSourceProvider(new PackageSourceProvider(defaultSettings)); - var tasks = new List>(); - - foreach (var request in requests) - { - var feeds = request.Sources - .Select(s => s?.Trim()) - .Where(s => !string.IsNullOrEmpty(s)) - .Distinct() - .Select(sourceProvider.CreateRepository); - tasks.Add(DownloadPackageAsync(request, feeds, cacheContext, throttle, logger, cts.Token)); - } - - var all = Task.WhenAll(tasks); - var delay = Task.Delay(timeout); - - var finished = await Task.WhenAny(all, delay); - if (ReferenceEquals(delay, finished)) - { - logger.LogError($"Timed out after {timeout.TotalSeconds}s"); - cts.Cancel(); - return false; - } - - if (!tasks.All(a => a.Result)) - { - logger.LogError("Failed to download all packages"); - return false; - } - - return true; - } - } - - private async Task DownloadPackageAsync( - PackageDownloadRequest request, - IEnumerable repositories, - SourceCacheContext cacheContext, - SemaphoreSlim throttle, - NuGet.Common.ILogger logger, - CancellationToken cancellationToken) - { - foreach (var repo in repositories) - { - var findPackageByIdResource = await repo.GetResourceAsync(cancellationToken); - - if (findPackageByIdResource == null) - { - logger.LogError($"{nameof(FindPackageByIdResource)} for '{repo}' could not be loaded."); - return false; - } - - using (var downloader = await findPackageByIdResource.GetPackageDownloaderAsync(request.Identity, cacheContext, logger, cancellationToken)) - { - if (downloader == null) - { - logger.LogInformation($"Package {request.Identity.Id} {request.Identity.Version} is not available on '{repo}'"); - // Skip to the next source if a package cannot be found in a given source. - continue; - } - - downloader.SetThrottle(throttle); - if (!await downloader.CopyNupkgFileToAsync(request.OutputPath, cancellationToken)) - { - logger.LogError($"Could not download {request.Identity.Id} {request.Identity.Version} from {repo}."); - return false; - } - } - - return true; - } - - logger.LogError($"{request.Identity.Id} {request.Identity.Version} is not available.'"); - return false; - } - } -} diff --git a/modules/KoreBuild.Tasks/Utilities/PackageVersionVariable.cs b/modules/KoreBuild.Tasks/Utilities/PackageVersionVariable.cs deleted file mode 100644 index 4131e2113..000000000 --- a/modules/KoreBuild.Tasks/Utilities/PackageVersionVariable.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.Build.Construction; - -namespace KoreBuild.Tasks.Utilities -{ - public class PackageVersionVariable - { - private readonly ProjectPropertyElement _element; - - public PackageVersionVariable(ProjectPropertyElement element, bool isReadOnly) - : this(element, element.Value?.Trim(), isReadOnly) - { - } - - public PackageVersionVariable(ProjectPropertyElement element, string version, bool isReadOnly) - { - _element = element ?? throw new ArgumentNullException(nameof(element)); - IsReadOnly = isReadOnly; - Name = element.Name.ToString(); - Version = version ?? string.Empty; - } - - public string Name { get; } - - public string Version - { - get => _element.Value; - private set => _element.Value = value; - } - - public bool IsReadOnly { get; private set; } - - public void UpdateVersion(string version) - { - if (IsReadOnly) - { - throw new InvalidOperationException("You cannot updated a pinned package version variable automatically"); - } - - Version = version; - } - - public void AddToGroup(ProjectPropertyGroupElement group) - { - group.AppendChild(_element); - } - - public void SetLabel(string label) - { - _element.Label = label; - } - } -} diff --git a/modules/KoreBuild.Tasks/module.props b/modules/KoreBuild.Tasks/module.props index 65848d3fb..1bc7ebbd4 100644 --- a/modules/KoreBuild.Tasks/module.props +++ b/modules/KoreBuild.Tasks/module.props @@ -11,20 +11,10 @@ - - - - - - - - - - $(KOREBUILD_DOTNET_ARCH) diff --git a/modules/KoreBuild.Tasks/module.targets b/modules/KoreBuild.Tasks/module.targets index f907ece4e..3cce8d116 100644 --- a/modules/KoreBuild.Tasks/module.targets +++ b/modules/KoreBuild.Tasks/module.targets @@ -3,9 +3,8 @@ GetToolsets;$(PrepareDependsOn) - InstallDotNet;CheckPackageReferences;$(RestoreDependsOn) + InstallDotNet;$(RestoreDependsOn) - false $(RepositoryRoot)korebuild.json $(RepositoryRoot)build\dependencies.props @@ -47,97 +46,6 @@ Downloads and extracts .NET Core shared runtimes and SDKs. InstallScript="$(_DotNetInstall)"/> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SHA256 diff --git a/test/BuildTools.Tasks.Tests/UnzipArchiveTest.cs b/test/BuildTools.Tasks.Tests/UnzipArchiveTest.cs deleted file mode 100644 index fcbf0c9d9..000000000 --- a/test/BuildTools.Tasks.Tests/UnzipArchiveTest.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Microsoft.AspNetCore.BuildTools; -using Xunit; - -using ZipArchiveStream = System.IO.Compression.ZipArchive; -using System.IO.Compression; - -namespace BuildTools.Tasks.Tests -{ - public class UnzipArchiveTest : IDisposable - { - private readonly string _tempDir; - - public UnzipArchiveTest() - { - _tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - Directory.CreateDirectory(_tempDir); - } - - [Fact] - public void UnzipsFile() - { - var files = new[] - { - "a.txt", - "dir/b.txt", - }; - - var dest = CreateZip(files); - var outDir = Path.Combine(_tempDir, "out"); - - var task = new UnzipArchive - { - File = dest, - Destination = outDir, - BuildEngine = new MockEngine(), - }; - - Assert.True(task.Execute(), "The task failed but should have passed."); - Assert.True(Directory.Exists(outDir), outDir + " does not exist"); - Assert.Equal(files.Length, task.OutputFiles.Length); - - Assert.All(task.OutputFiles, - f => Assert.True(Path.IsPathRooted(f.ItemSpec), $"Entry {f} should be a fullpath rooted")); - - foreach (var file in files) - { - var outFile = Path.Combine(outDir, file); - Assert.True(File.Exists(outFile), outFile + " does not exist"); - } - } - - [Fact] - public void UnzipsSubdirectories() - { - var files = new[] - { - "a/b/c/d.dll", - "e/f/j/k/l.json", - "e/f/m/n/o.json" - }; - - var dest = CreateZip(files); - var outDir = Path.Combine(_tempDir, "out"); - - var task = new UnzipArchive - { - File = dest, - Destination = outDir, - BuildEngine = new MockEngine(), - }; - - Assert.True(task.Execute(), "The task failed but should have passed."); - Assert.True(Directory.Exists(outDir), outDir + " does not exist"); - Assert.Equal(files.Length, task.OutputFiles.Length); - - Assert.All(task.OutputFiles, - f => Assert.True(Path.IsPathRooted(f.ItemSpec), $"Entry {f} should be a fullpath rooted")); - - foreach (var file in files) - { - var outFile = Path.Combine(outDir, file); - Assert.True(File.Exists(outFile), outFile + " does not exist"); - } - } - - [Fact] - public void Overwrites() - { - var files = new[] - { - "a.txt", - "dir/b.txt" - }; - - var dest = CreateZip(files); - var outDir = Path.Combine(_tempDir, "out"); - - var task = new UnzipArchive - { - File = dest, - Destination = outDir, - BuildEngine = new MockEngine(), - Overwrite = true - }; - - Directory.CreateDirectory(outDir); - - // Create a.txt before trying to unzip - var path = Path.Combine(outDir, "a.txt"); - File.WriteAllText(path, "contents!"); - Assert.True(task.Execute(), "The task failed but should have passed."); - Assert.Empty(File.ReadAllText(path)); - } - - [Fact] - public void DoesNotOverwrite() - { - var files = new[] - { - "a.txt", - "dir/b.txt" - }; - - var dest = CreateZip(files); - var outDir = Path.Combine(_tempDir, "out"); - - var task = new UnzipArchive - { - File = dest, - Destination = outDir, - BuildEngine = new MockEngine(), - Overwrite = false - }; - - Directory.CreateDirectory(outDir); - - // Create a.txt before trying to unzip - var path = Path.Combine(outDir, "a.txt"); - var contents = "contents!"; - File.WriteAllText(path, contents); - - Assert.Throws(() => task.Execute()); - - Assert.Equal(contents, File.ReadAllText(path)); - } - - [Fact] - public void ItNormalizesBacklashesInPath() - { - var files = new[] - { - @"dir\b.txt" - }; - - var dest = CreateZip(files); - var outDir = Path.Combine(_tempDir, "out"); - - var engine = new MockEngine(); - var task = new UnzipArchive - { - File = dest, - Destination = outDir, - BuildEngine = engine, - Overwrite = false - }; - - Assert.True(task.Execute(), "The task failed but should have passed."); - Assert.True(File.Exists(Path.Combine(outDir, "dir", "b.txt")), "File should exist."); - } - - private string CreateZip(string[] files) - { - var dest = Path.Combine(_tempDir, "test.zip"); - - using (var fileStream = new FileStream(dest, FileMode.Create)) - using (var zipStream = new ZipArchiveStream(fileStream, ZipArchiveMode.Create)) - { - foreach (var file in files) - { - zipStream.CreateEntry(file); - } - } - - return dest; - } - - public void Dispose() - { - Directory.Delete(_tempDir, recursive: true); - } - } -} diff --git a/test/BuildTools.Tasks.Tests/ZipArchiveTest.cs b/test/BuildTools.Tasks.Tests/ZipArchiveTest.cs deleted file mode 100644 index c39ad48bd..000000000 --- a/test/BuildTools.Tasks.Tests/ZipArchiveTest.cs +++ /dev/null @@ -1,220 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.BuildTools; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Xunit; - -using ZipArchiveStream = System.IO.Compression.ZipArchive; - -namespace BuildTools.Tasks.Tests -{ - public class ZipArchiveTest : IDisposable - { - private readonly string _tempDir; - - public ZipArchiveTest() - { - _tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - Directory.CreateDirectory(_tempDir); - } - - [Fact] - public void ZipsLinkItems() - { - var inputFile = Path.Combine(_tempDir, "..", Guid.NewGuid().ToString()); - var dest = Path.Combine(_tempDir, "test.zip"); - var linkItem = new TaskItem(inputFile); - linkItem.SetMetadata("Link", "temp/temp/temp/file.txt"); - try - { - File.WriteAllText(inputFile, ""); - var task = new ZipArchive - { - SourceFiles = new[] { linkItem }, - WorkingDirectory = Path.Combine(_tempDir, "temp"), - File = dest, - BuildEngine = new MockEngine(), - }; - Assert.True(task.Execute()); - - using (var fileStream = new FileStream(dest, FileMode.Open)) - using (var zipStream = new ZipArchiveStream(fileStream)) - { - var entry = Assert.Single(zipStream.Entries); - Assert.Equal("temp/temp/temp/file.txt", entry.FullName); - } - } - finally - { - File.Delete(inputFile); - } - } - - [Fact] - public void CreatesZip() - { - var files = new[] - { - "a.txt", - "dir/b.txt", - @"dir\c.txt", - }; - - var dest = Path.Combine(_tempDir, "test.zip"); - Assert.False(File.Exists(dest)); - - var task = new ZipArchive - { - SourceFiles = CreateItems(files).ToArray(), - WorkingDirectory = _tempDir, - File = dest, - Overwrite = true, - BuildEngine = new MockEngine(), - }; - - Assert.True(task.Execute()); - Assert.True(File.Exists(dest)); - - using (var fileStream = new FileStream(dest, FileMode.Open)) - using (var zipStream = new ZipArchiveStream(fileStream)) - { - Assert.Equal(files.Length, zipStream.Entries.Count); - Assert.Collection(zipStream.Entries, - a => Assert.Equal("a.txt", a.FullName), - b => Assert.Equal("dir/b.txt", b.FullName), - c => Assert.Equal("dir/c.txt", c.FullName)); - } - } - - [Fact] - public void FailsIfFileExists() - { - var files = new[] - { - "test.txt", - }; - - var dest = Path.Combine(_tempDir, "test.zip"); - File.WriteAllText(dest, "Original"); - - var task = new ZipArchive - { - SourceFiles = CreateItems(files).ToArray(), - WorkingDirectory = _tempDir, - File = dest, - Overwrite = false, - BuildEngine = new MockEngine { ContinueOnError = true }, - }; - - Assert.False(task.Execute(), "Task should fail"); - Assert.Equal("Original", File.ReadAllText(dest)); - } - - [Fact] - public void OverwriteReplacesEntireZip() - { - var files1 = new[] - { - "a.txt", - "dir/b.txt", - @"dir\c.txt", - }; - - var files2 = new[] - { - "test.txt", - }; - - var dest = Path.Combine(_tempDir, "test.zip"); - Assert.False(File.Exists(dest)); - - var task = new ZipArchive - { - SourceFiles = CreateItems(files1).ToArray(), - WorkingDirectory = _tempDir, - File = dest, - BuildEngine = new MockEngine(), - }; - - Assert.True(task.Execute()); - Assert.True(File.Exists(dest)); - - task = new ZipArchive - { - SourceFiles = CreateItems(files2).ToArray(), - WorkingDirectory = _tempDir, - File = dest, - Overwrite = true, - BuildEngine = new MockEngine(), - }; - - Assert.True(task.Execute()); - Assert.True(File.Exists(dest)); - - using (var fileStream = File.OpenRead(dest)) - using (var zipStream = new ZipArchiveStream(fileStream)) - { - var entry = Assert.Single(zipStream.Entries); - Assert.Equal("test.txt", entry.FullName); - } - } - - [Fact] - public void FailsForEmptyFileName() - { - var inputFile = Path.Combine(_tempDir, "..", Guid.NewGuid().ToString()); - var dest = Path.Combine(_tempDir, "test.zip"); - var linkItem = new TaskItem(inputFile); - linkItem.SetMetadata("Link", "temp/"); - try - { - File.WriteAllText(inputFile, ""); - var mock = new MockEngine { ContinueOnError = true }; - var task = new ZipArchive - { - SourceFiles = new[] { linkItem }, - WorkingDirectory = Path.Combine(_tempDir, "temp"), - File = dest, - BuildEngine = mock, - }; - - Assert.False(task.Execute(), "Task should fail"); - Assert.NotEmpty(mock.Errors); - - using (var fileStream = new FileStream(dest, FileMode.Open)) - using (var zipStream = new ZipArchiveStream(fileStream)) - { - Assert.Empty(zipStream.Entries); - } - } - finally - { - File.Delete(inputFile); - } - } - - private IEnumerable CreateItems(string[] files) - { - foreach (var file in files) - { - var path = Path.Combine(_tempDir, file); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - File.WriteAllText(path.Replace('\\', '/'), ""); - // intentionally allow item spec to contain \ and / - // this tests that MSBuild normalizes before we create zip entries - yield return new TaskItem(path); - } - } - - public void Dispose() - { - Directory.Delete(_tempDir, recursive: true); - } - } -} diff --git a/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs b/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs index 0febb9a1b..dd810e789 100644 --- a/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs +++ b/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs @@ -33,7 +33,7 @@ public void FullBuildCompletes() { var app = _fixture.CreateTestApp("SimpleRepo"); - var build = app.ExecuteBuild(_output, "/p:BuildNumber=0001"); + var build = app.ExecuteBuild(_output, "/p:BuildNumber=0001", "/p:DisableCodeSigning=true"); Assert.Equal(0, build); @@ -52,14 +52,9 @@ public void FullBuildCompletes() { Assert.Empty(reader.GetFiles().Where(p => Path.GetExtension(p).Equals(".pdb", StringComparison.OrdinalIgnoreCase))); } - - // /t:TestNuGetPush - Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.CliTool.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages"); - Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.Lib.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages"); - Assert.True(File.Exists(Path.Combine(app.WorkingDirectory, "obj", "tmp-nuget", "Simple.Sources.1.0.0-beta-0001.nupkg")), "Build done a test push of all the packages"); } - [Fact] + [Fact(Skip = "Blocked on https://github.com/dotnet/sdk/issues/2867")] public void BuildOfGlobalCliToolIncludesShims() { var app = _fixture.CreateTestApp("RepoWithGlobalTool"); @@ -121,84 +116,5 @@ public void BuildShouldReturnNonZeroCode() Assert.NotEqual(0, build); } - - [DockerExistsFact(Skip = "winservercore currently fails on AppVeyor due to breaking changes in winservercore 1710")] - public void DockerSuccessful() - { - var app = _fixture.CreateTestApp("SimpleRepo"); - var platform = "jessie"; - - var dockerPlatform = GetDockerPlatform(); - if (dockerPlatform == OSPlatform.Windows) - { - platform = "winservercore"; - } - - var build = app.ExecuteRun(_output, new string[] { "docker-build", "-Path", app.WorkingDirectory }, platform, "/p:BuildNumber=0001"); - - Assert.Equal(0, build); - } - - private static OSPlatform GetDockerPlatform() - { - var startInfo = new ProcessStartInfo("docker", @"version -f ""{{ .Server.Os }}""") - { - RedirectStandardOutput = true, - UseShellExecute = false, - }; - - using (var process = Process.Start(startInfo)) - { - var output = process.StandardOutput.ReadToEnd().Trim(); - - OSPlatform result; - switch (output) - { - case "windows": - result = OSPlatform.Windows; - break; - case "linux": - result = OSPlatform.Linux; - break; - default: - throw new NotImplementedException($"No default for docker platform {output}"); - } - - return result; - } - } - } - - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class DockerExistsFactAttribute : FactAttribute - { - public DockerExistsFactAttribute() - { - if (!HasDocker()) - { - Skip = "Docker must be installed to run this test."; - } - } - - private static bool HasDocker() - { - try - { - var startInfo = new ProcessStartInfo("docker", "--version") - { - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - }; - using (Process.Start(startInfo)) - { - return true; - } - } - catch (Win32Exception) - { - return false; - } - } } } diff --git a/test/KoreBuild.Tasks.Tests/CheckPackageReferenceTests.cs b/test/KoreBuild.Tasks.Tests/CheckPackageReferenceTests.cs deleted file mode 100644 index a83450ff5..000000000 --- a/test/KoreBuild.Tasks.Tests/CheckPackageReferenceTests.cs +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using BuildTools.Tasks.Tests; -using Microsoft.Build.Utilities; -using System.IO; -using Xunit; -using Xunit.Abstractions; - -namespace KoreBuild.Tasks.Tests -{ - [Collection(nameof(MSBuildTestCollection))] - public class CheckPackageReferenceTests : TaskTestBase - { - public CheckPackageReferenceTests(ITestOutputHelper output, MSBuildTestCollectionFixture fixture) : base(output, fixture) - { - } - - [Fact] - public void ItAllowsPinnedAndUnpinnedVersions() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - 1.0.0 - - - - - - 1.0.0 - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - $(BaseLinePackageVersion) - - - -".Replace('`', '"')); - - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - DependenciesFile = depsProps, - Projects = new[] { new TaskItem(csproj) } - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - } - - [Fact] - public void PassesWhenAllRequirementsAreSatisifed() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - 1.0.0 - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - $(AspNetCorePackageVersion) - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - DependenciesFile = depsProps, - Projects = new[] { new TaskItem(csproj) } - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - } - - [Fact] - public void IgnoresUpdateAndRemoveItems() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - DependenciesFile = depsProps, - Projects = new[] { new TaskItem(csproj) } - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - } - - [Fact] - public void FailsWhenDependenciesHasNoPropGroup() - { - var depsFile = Path.Combine(TempDir, "deps.props"); - File.WriteAllText(depsFile, $@" - - - 1.0.0 - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - Projects = new[] { new TaskItem(depsFile) }, - DependenciesFile = depsFile, - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - Assert.NotEmpty(MockEngine.Warnings); - Assert.Contains(MockEngine.Warnings, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.PackageRefPropertyGroupNotFound); - } - - [Fact] - public void FailsWhenVariableIsNotInDependenciesPropsFile() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - Projects = new[] { new TaskItem(csproj) }, - DependenciesFile = depsProps, - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - Assert.NotEmpty(MockEngine.Errors); - Assert.Contains(MockEngine.Errors, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.VariableNotFoundInDependenciesPropsFile); - } - - [Fact] - public void FailsWhenPackageVersionFloat() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - 1.0.0-* - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - Projects = new[] { new TaskItem(csproj) }, - DependenciesFile = depsProps, - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - Assert.NotEmpty(MockEngine.Errors); - Assert.Contains(MockEngine.Errors, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.PackageRefHasFloatingVersion); - } - - [Fact] - public void FailsWhenPackageVersionIsInvalid() - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - 1 - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - Projects = new[] { new TaskItem(csproj) }, - DependenciesFile = depsProps, - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - Assert.NotEmpty(MockEngine.Errors); - Assert.Contains(MockEngine.Errors, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.InvalidPackageVersion); - } - - [Theory] - [InlineData("1.0.0")] - [InlineData("1.0.0-$(Suffix)")] - [InlineData("$(Prefix)-1.0.0-$(Suffix)")] - [InlineData("$(Prefix)-1.0.0")] - public void FailsWhenPackagesReferenceVersionDoesNotCompletelyUseVariables(string version) - { - var depsProps = Path.Combine(TempDir, "dependencies.props"); - File.WriteAllText(depsProps, $@" - - - -".Replace('`', '"')); - - var csproj = Path.Combine(TempDir, "Test.csproj"); - File.WriteAllText(csproj, $@" - - - - - -".Replace('`', '"')); - - MockEngine.ContinueOnError = true; - var task = new CheckPackageReferences - { - BuildEngine = MockEngine, - Projects = new[] { new TaskItem(csproj) }, - DependenciesFile = depsProps, - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - Assert.NotEmpty(MockEngine.Errors); - var error = Assert.Single(MockEngine.Errors, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.PackageRefHasLiteralVersion); - Assert.Equal(4, error.LineNumber); - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/DependencyVersionsFileTests.cs b/test/KoreBuild.Tasks.Tests/DependencyVersionsFileTests.cs deleted file mode 100644 index 8b030706f..000000000 --- a/test/KoreBuild.Tasks.Tests/DependencyVersionsFileTests.cs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.IO; -using System.Linq; -using BuildTools.Tasks.Tests; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Utilities; -using Xunit; -using Xunit.Abstractions; - -namespace KoreBuild.Tasks.Tests -{ - [Collection(nameof(MSBuildTestCollection))] - public class DependencyVersionsFileTests : IDisposable - { - private readonly string _tempFile; - private readonly ITestOutputHelper _output; - - public DependencyVersionsFileTests(ITestOutputHelper output, MSBuildTestCollectionFixture fixture) - { - _output = output; - fixture.InitializeEnvironment(output); - _tempFile = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName()); - } - - public void Dispose() - { - if (File.Exists(_tempFile)) - { - File.Delete(_tempFile); - } - } - - [Fact] - public void ItSortsVariablesAlphabetically() - { - var depsFile = DependencyVersionsFile.Create(addOverrideImport: true); - depsFile.Update("XyzPackageVersion", "123"); - depsFile.Update("AbcPackageVersion", "456"); - depsFile.Save(_tempFile); - - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - var versions = Assert.Single(project.PropertyGroups, p => p.Label == DependencyVersionsFile.AutoPackageVersionsLabel); - Assert.Collection(versions.Properties, - v => Assert.Equal("AbcPackageVersion", v.Name), - v => Assert.Equal("XyzPackageVersion", v.Name)); - } - - [Fact] - public void SetIsCaseInsensitive() - { - var depsFile = DependencyVersionsFile.Create(addOverrideImport: true); - depsFile.Update("XunitRunnerVisualStudioVersion", "2.3.0"); - depsFile.Update("XunitRunnerVisualstudioVersion", "2.4.0"); - depsFile.Save(_tempFile); - - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - var versions = Assert.Single(project.PropertyGroups, p => p.Label == DependencyVersionsFile.AutoPackageVersionsLabel); - var prop = Assert.Single(versions.Properties); - Assert.Equal("XunitRunnerVisualStudioVersion", prop.Name); - Assert.Equal("2.4.0", prop.Value); - } - - [Theory] - [InlineData("Microsoft.Data.Sqlite", "MicrosoftDataSqlitePackageVersion")] - [InlineData("SQLitePCLRaw.bundle_green", "SQLitePCLRawBundleGreenPackageVersion")] - [InlineData("runtime.win-x64.Microsoft.NETCore", "RuntimeWinX64MicrosoftNETCorePackageVersion")] - public void GeneratesVariableName(string id, string varName) - { - Assert.Equal(varName, DependencyVersionsFile.GetVariableName(id)); - } - - [Fact] - public void AdditionalImportsAreAdded_WithOverrideImportFalse() - { - // Arrange - var path = "obj/test.props"; - var depsFile = DependencyVersionsFile.Create(addOverrideImport: false, additionalImports: new[] { path }); - depsFile.Save(_tempFile); - - // Act - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - // Assert - var import = Assert.Single(project.Imports); - Assert.Equal(path, import.Project); - } - - [Fact] - public void AdditionalImportsAreAdded_WithOverrideImportTrue() - { - // Arrange - var path = "obj/external.props"; - var depsFile = DependencyVersionsFile.Create(addOverrideImport: true, additionalImports: new[] { path }); - depsFile.Save(_tempFile); - - // Act - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - // Assert - Assert.Collection( - project.Imports, - import => Assert.Equal(path, import.Project), - import => Assert.Equal("$(DotNetPackageVersionPropsPath)", import.Project)); - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/DownloadNuGetPackagesTests.cs b/test/KoreBuild.Tasks.Tests/DownloadNuGetPackagesTests.cs deleted file mode 100644 index a1a72f3ef..000000000 --- a/test/KoreBuild.Tasks.Tests/DownloadNuGetPackagesTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.IO; -using BuildTools.Tasks.Tests; -using Microsoft.Build.Utilities; -using Xunit; -using Xunit.Abstractions; -using Task = System.Threading.Tasks.Task; - -namespace KoreBuild.Tasks.Tests -{ - public class DownloadNuGetPackagesTest - { - private readonly ITestOutputHelper _output; - - public DownloadNuGetPackagesTest(ITestOutputHelper output) - { - _output = output; - } - - [Fact] - public async Task ItDownloadPackages() - { - var packages = new[] - { - new TaskItem("Newtonsoft.Json", new Hashtable - { - ["Version"] = "9.0.1", - ["Source"] = " https://api.nuget.org/v3/index.json ; ;https://api.nuget.org/v3/index.json; https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json " - }), - }; - - var task = new DownloadNuGetPackages - { - Packages = packages, - DestinationFolder = AppContext.BaseDirectory, - BuildEngine = new MockEngine(_output), - TimeoutSeconds = 120, - }; - var expectedPath = Path.Combine(AppContext.BaseDirectory, "newtonsoft.json.9.0.1.nupkg").Replace('\\', '/'); - if (File.Exists(expectedPath)) - { - File.Delete(expectedPath); - } - - Assert.False(File.Exists(expectedPath), "The file should not exist yet"); - Assert.True(await task.ExecuteAsync(), "Task should pass"); - var file = Assert.Single(task.Files); - Assert.Equal(expectedPath, file.ItemSpec.Replace('\\', '/')); - Assert.True(File.Exists(expectedPath), "The file should exist"); - } - - [Fact] - public async Task ItFailsForPackagesThatDoNotExist() - { - var packages = new[] - { - new TaskItem("SomePackage", new Hashtable { ["Version"] = "1.0.0", ["Source"] = AppContext.BaseDirectory }), - }; - - var engine = new MockEngine(_output) { ContinueOnError = true }; - var task = new DownloadNuGetPackages - { - Packages = packages, - DestinationFolder = AppContext.BaseDirectory, - BuildEngine = engine, - TimeoutSeconds = 120, - }; - - Assert.False(await task.ExecuteAsync(), "Task should fail"); - Assert.NotEmpty(engine.Errors); - Assert.Contains(engine.Errors, m => m.Message.Contains("SomePackage 1.0.0 is not available")); - } - - [Fact] - public async Task ItFindsPackageWhenMultipleFeedsAreSpecified() - { - var packages = new[] - { - new TaskItem("Newtonsoft.Json", new Hashtable { ["Version"] = "9.0.1", ["Source"] = $"{AppContext.BaseDirectory};https://api.nuget.org/v3/index.json"} ), - }; - - var task = new DownloadNuGetPackages - { - Packages = packages, - DestinationFolder = AppContext.BaseDirectory, - BuildEngine = new MockEngine(_output), - TimeoutSeconds = 120, - }; - var expectedPath = Path.Combine(AppContext.BaseDirectory, "newtonsoft.json.9.0.1.nupkg").Replace('\\', '/'); - if (File.Exists(expectedPath)) - { - File.Delete(expectedPath); - } - - Assert.False(File.Exists(expectedPath), "The file should not exist yet"); - Assert.True(await task.ExecuteAsync(), "Task should pass"); - var file = Assert.Single(task.Files); - Assert.Equal(expectedPath, file.ItemSpec.Replace('\\', '/')); - Assert.True(File.Exists(expectedPath), "The file should exist"); - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/GenerateDependenciesPropsFileTests.cs b/test/KoreBuild.Tasks.Tests/GenerateDependenciesPropsFileTests.cs deleted file mode 100644 index 0748aec14..000000000 --- a/test/KoreBuild.Tasks.Tests/GenerateDependenciesPropsFileTests.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.IO; -using BuildTools.Tasks.Tests; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Xunit; -using Xunit.Abstractions; - -namespace KoreBuild.Tasks.Tests -{ - [Collection(nameof(MSBuildTestCollection))] - public class GenerateDependenciesPropsFileTests : IDisposable - { - private readonly ITestOutputHelper _output; - private readonly string _tempDir; - - public GenerateDependenciesPropsFileTests(ITestOutputHelper output, MSBuildTestCollectionFixture fixture) - { - _output = output; - _tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - Directory.CreateDirectory(_tempDir); - fixture.InitializeEnvironment(output); - } - - [Fact] - public void GeneratesVariableName() - { - var generatedFile = Path.Combine(_tempDir, "deps.props"); - var csproj = Path.Combine(_tempDir, "test.csproj"); - CreateProject(csproj, "1.2.3"); - - var task = new GenerateDependenciesPropsFile - { - BuildEngine = new MockEngine(_output), - DependenciesFile = generatedFile, - Projects = new[] { new TaskItem(csproj) }, - Properties = Array.Empty(), - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - var depsFile = ProjectRootElement.Open(generatedFile); - _output.WriteLine(File.ReadAllText(generatedFile)); - var pg = Assert.Single(depsFile.PropertyGroups, p => p.Label == DependencyVersionsFile.AutoPackageVersionsLabel); - var prop = Assert.Single(pg.Properties, p => p.Name == "MyDependencyPackageVersion"); - Assert.Equal("1.2.3", prop.Value); - } - - [Fact] - public void IgnoresImplicitlyDefinedVariables() - { - var generatedFile = Path.Combine(_tempDir, "deps.props"); - var csproj = Path.Combine(_tempDir, "test.csproj"); - File.WriteAllText(csproj, $@" - - - netstandard2.0 - -".Replace('`', '"')); - - var task = new GenerateDependenciesPropsFile - { - BuildEngine = new MockEngine(_output), - DependenciesFile = generatedFile, - Projects = new[] { new TaskItem(csproj) }, - Properties = Array.Empty(), - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - var depsFile = ProjectRootElement.Open(generatedFile); - _output.WriteLine(File.ReadAllText(generatedFile)); - var pg = Assert.Single(depsFile.PropertyGroups, p => p.Label == DependencyVersionsFile.AutoPackageVersionsLabel); - Assert.Empty(pg.Properties); - } - - [Fact] - public void FailsWhenConflictingVersions() - { - var generatedFile = Path.Combine(_tempDir, "deps.props"); - var csproj1 = Path.Combine(_tempDir, "test1.csproj"); - var csproj2 = Path.Combine(_tempDir, "test2.csproj"); - CreateProject(csproj1, "1.2.3"); - CreateProject(csproj2, "4.5.6"); - - var engine = new MockEngine(_output) { ContinueOnError = true }; - var task = new GenerateDependenciesPropsFile - { - BuildEngine = engine, - DependenciesFile = generatedFile, - Projects = new[] { new TaskItem(csproj1), new TaskItem(csproj2) }, - Properties = Array.Empty(), - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - Assert.Single(engine.Errors, e => e.Code == KoreBuildErrors.Prefix + KoreBuildErrors.ConflictingPackageReferenceVersions); - } - - [Fact] - public void DoesNotFailWhenConflictingVersionsAreSuppressed() - { - var generatedFile = Path.Combine(_tempDir, "deps.props"); - var csproj1 = Path.Combine(_tempDir, "test1.csproj"); - var csproj2 = Path.Combine(_tempDir, "test2.csproj"); - CreateProject(csproj1, "1.2.3"); - - File.WriteAllText(csproj2, $@" - - - netstandard2.0 - - - - -".Replace('`', '"')); - - var task = new GenerateDependenciesPropsFile - { - BuildEngine = new MockEngine(_output), - DependenciesFile = generatedFile, - Projects = new[] { new TaskItem(csproj1), new TaskItem(csproj2) }, - Properties = Array.Empty(), - }; - - Assert.True(task.Execute(), "Task is expected to oass"); - } - - private static void CreateProject(string csprojFilePath, string version) - { - File.WriteAllText(csprojFilePath, $@" - - - netstandard2.0 - - - - -".Replace('`', '"')); - } - - - public void Dispose() - { - Directory.Delete(_tempDir, recursive: true); - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/GeneratePackageVersionPropsFileTests.cs b/test/KoreBuild.Tasks.Tests/GeneratePackageVersionPropsFileTests.cs deleted file mode 100644 index 86c731b8c..000000000 --- a/test/KoreBuild.Tasks.Tests/GeneratePackageVersionPropsFileTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.IO; -using BuildTools.Tasks.Tests; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using Xunit; -using Xunit.Abstractions; - -namespace KoreBuild.Tasks.Tests -{ - [Collection(nameof(MSBuildTestCollection))] - public class GeneratePackageVersionPropsFileTests : IDisposable - { - private readonly ITestOutputHelper _output; - private readonly string _tempFile; - - public GeneratePackageVersionPropsFileTests(ITestOutputHelper output, MSBuildTestCollectionFixture fixture) - { - _output = output; - _tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - fixture.InitializeEnvironment(output); - } - - [Fact] - public void GeneratesFile() - { - var engine = new MockEngine(_output); - var task = new GeneratePackageVersionPropsFile - { - BuildEngine = engine, - Packages = new[] - { - // Order is important. These are intentionally reverse sorted to ensure the generated file sorts properties by prop name - new TaskItem("Newtonsoft.Json", new Hashtable{["Version"] = "10.0.3", ["VariableName"] = "JsonNetVersion"}), - new TaskItem("Microsoft.Azure", new Hashtable{["Version"] = "1.2.0"}), - new TaskItem("Another.Package", new Hashtable{["Version"] = "0.0.1", ["TargetFramework"] = "netstandard1.0"}), - }, - OutputPath = _tempFile, - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - Assert.Empty(project.Imports); - Assert.Empty(project.ImportGroups); - - var defaultPropGroup = Assert.Single(project.PropertyGroups, pg => string.IsNullOrEmpty(pg.Label)); - var allProjectsProp = Assert.Single(defaultPropGroup.Properties); - Assert.Equal("MSBuildAllProjects", allProjectsProp.Name); - Assert.Empty(allProjectsProp.Condition); - Assert.Equal("$(MSBuildAllProjects);$(MSBuildThisFileFullPath)", allProjectsProp.Value); - - var versions = Assert.Single(project.PropertyGroups, pg => pg.Label == DependencyVersionsFile.AutoPackageVersionsLabel); - - // Order is important. These should be sorted. - Assert.Collection(versions.Properties, - p => - { - Assert.Equal("AnotherPackagePackageVersion", p.Name); - Assert.Equal("Another.Package", p.Label); - Assert.Equal("0.0.1", p.Value); - Assert.Empty(p.Condition); - }, - p => - { - Assert.Equal("JsonNetVersion", p.Name); - Assert.Equal("Newtonsoft.Json", p.Label); - Assert.Equal("10.0.3", p.Value); - Assert.Empty(p.Condition); - }, - p => - { - Assert.Equal("MicrosoftAzurePackageVersion", p.Name); - Assert.Equal("Microsoft.Azure", p.Label); - Assert.Equal("1.2.0", p.Value); - Assert.Empty(p.Condition); - }); - } - - [Fact] - public void GeneratesImport() - { - var task = new GeneratePackageVersionPropsFile - { - BuildEngine = new MockEngine(_output), - Packages = Array.Empty(), - AddOverrideImport = true, - OutputPath = _tempFile, - }; - - Assert.True(task.Execute(), "Task is expected to pass"); - var project = ProjectRootElement.Open(_tempFile); - _output.WriteLine(File.ReadAllText(_tempFile)); - - var import = Assert.Single(project.Imports); - Assert.Equal("$(DotNetPackageVersionPropsPath)", import.Project); - Assert.Equal(" '$(DotNetPackageVersionPropsPath)' != '' ", import.Condition); - } - - public void Dispose() - { - if (File.Exists(_tempFile)) - { - File.Delete(_tempFile); - } - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/InstallToolsetsTests.cs b/test/KoreBuild.Tasks.Tests/InstallToolsetsTests.cs deleted file mode 100644 index c66e67bf8..000000000 --- a/test/KoreBuild.Tasks.Tests/InstallToolsetsTests.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Runtime.InteropServices; -using BuildTools.Tasks.Tests; -using Xunit; - -namespace KoreBuild.Tasks.Tests -{ - public class InstallToolsetsTests : IDisposable - { - private readonly string _configFile; - - public InstallToolsetsTests() - { - _configFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - } - - public void Dispose() - { - if (File.Exists(_configFile)) - { - File.Delete(_configFile); - } - } - - [Fact] - public void FailsIfVsIsRequiredOnNonWindows() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return; - } - - File.WriteAllText(_configFile, @" -{ - ""toolsets"": { - ""visualstudio"": { - ""required"": [""macos"", ""linux""] - }, - } -}"); - var task = new InstallToolsets - { - BuildEngine = new MockEngine { ContinueOnError = true }, - ConfigFile = _configFile, - }; - - Assert.False(task.Execute(), "Task is expected to fail"); - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/KoreBuild.Tasks.Tests.csproj b/test/KoreBuild.Tasks.Tests/KoreBuild.Tasks.Tests.csproj index a0cfe0a82..2ec3473a6 100644 --- a/test/KoreBuild.Tasks.Tests/KoreBuild.Tasks.Tests.csproj +++ b/test/KoreBuild.Tasks.Tests/KoreBuild.Tasks.Tests.csproj @@ -28,11 +28,5 @@ - - - PreserveNewest - - - diff --git a/test/KoreBuild.Tasks.Tests/PackNuSpecTests.cs b/test/KoreBuild.Tasks.Tests/PackNuSpecTests.cs deleted file mode 100644 index bdadd3e38..000000000 --- a/test/KoreBuild.Tasks.Tests/PackNuSpecTests.cs +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using BuildTools.Tasks.Tests; -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; -using NuGet.Frameworks; -using NuGet.Packaging; -using NuGet.Versioning; -using Xunit; - -namespace KoreBuild.Tasks.Tests -{ - public class PackNuSpecTests : IDisposable - { - private readonly string _tempDir; - - public PackNuSpecTests() - { - _tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - Directory.CreateDirectory(_tempDir); - } - - [Fact] - public void CreatesPackage() - { - var outputPath = Path.Combine(_tempDir, $"TestPackage.1.0.0.nupkg"); - Directory.CreateDirectory(Path.Combine(_tempDir, "tools")); - Directory.CreateDirectory(Path.Combine(_tempDir, "lib", "netstandard2.0")); - File.WriteAllText(Path.Combine(_tempDir, "tools", "test.sh"), ""); - File.WriteAllText(Path.Combine(_tempDir, "lib", "netstandard2.0", "TestPackage.dll"), ""); - - var nuspec = CreateNuspec(@" - - - - TestPackage - 1.0.0 - Test - Test - - - - - - - "); - - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = new MockEngine(), - DestinationFolder = _tempDir, - }; - - Assert.True(task.Execute(), "The task should have passed"); - Assert.True(File.Exists(outputPath), "Should have produced a nupkg file in " + _tempDir); - var result = Assert.Single(task.Packages); - Assert.Equal(outputPath, result.ItemSpec); - using (var reader = new PackageArchiveReader(outputPath)) - { - var libItems = reader.GetLibItems().ToList(); - var libItem = Assert.Single(libItems); - Assert.Equal(FrameworkConstants.CommonFrameworks.NetStandard20, libItem.TargetFramework); - var assembly = Assert.Single(libItem.Items); - Assert.Equal("lib/netstandard2.0/TestPackage.dll", assembly); - - Assert.Contains(reader.GetFiles(), f => f == "tools/test.sh"); - } - } - - [Fact] - public void AppliesProperties() - { - var nuspec = CreateNuspec(@" - - - - HasProperties - $version$ - Microsoft - $description$ - $copyright$ - - - - - - - "); - - var version = "1.2.3"; - var description = "A test package\n\n\nwith newlines"; - var outputPath = Path.Combine(_tempDir, $"HasProperties.{version}.nupkg"); - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = new MockEngine(), - DestinationFolder = _tempDir, - Properties = new[] { $"version={version}", "", "", $" description ={description}", "copyright=", }, - }; - - Assert.True(task.Execute(), "The task should have passed"); - Assert.True(File.Exists(outputPath), "Should have produced a nupkg file in " + _tempDir); - - using (var reader = new PackageArchiveReader(outputPath)) - { - var metadata = new PackageBuilder(reader.GetNuspec(), basePath: null); - Assert.Equal(version, metadata.Version.ToString()); - Assert.Empty(metadata.Copyright); - Assert.Equal(description, metadata.Description); - } - } - - [Fact] - public void AddsDependencies() - { - var nuspec = CreateNuspec(@" - - - - HasDependencies - 1.0.0 - Test - Test - - - - - - - "); - - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = new MockEngine(), - DestinationFolder = _tempDir, - Dependencies = new[] - { - new TaskItem("OtherPackage", new Hashtable { ["Version"] = "[1.0.0, 2.0.0)"}), - new TaskItem("PackageInTfm", new Hashtable { ["TargetFramework"] = "netstandard1.0", ["Version"] = "0.1.0-beta" }), - new TaskItem("PackageInTfm", new Hashtable { ["TargetFramework"] = "netstandard1.1", ["Version"] = "0.2.0-beta" }), - } - }; - - Assert.True(task.Execute(), "The task should have passed"); - var result = Assert.Single(task.Packages); - - using (var reader = new PackageArchiveReader(result.ItemSpec)) - { - var metadata = new PackageBuilder(reader.GetNuspec(), basePath: null); - - var noTfmGroup = Assert.Single(metadata.DependencyGroups, d => d.TargetFramework.Equals(NuGetFramework.UnsupportedFramework)); - Assert.Equal(2, noTfmGroup.Packages.Count()); - Assert.Single(noTfmGroup.Packages, p => p.Id == "OtherPackage" && p.VersionRange.Equals(VersionRange.Parse("[1.0.0, 2.0.0)"))); - Assert.Single(noTfmGroup.Packages, p => p.Id == "AlreadyInNuspec" && p.VersionRange.Equals(VersionRange.Parse("[2.0.0]"))); - - var netstandard10Group = Assert.Single(metadata.DependencyGroups, d => d.TargetFramework.Equals(FrameworkConstants.CommonFrameworks.NetStandard10)); - var package1 = Assert.Single(netstandard10Group.Packages); - Assert.Equal("PackageInTfm", package1.Id); - Assert.Equal(VersionRange.Parse("0.1.0-beta"), package1.VersionRange); - - var netstandard11Group = Assert.Single(metadata.DependencyGroups, d => d.TargetFramework.Equals(FrameworkConstants.CommonFrameworks.NetStandard11)); - var package2 = Assert.Single(netstandard11Group.Packages); - Assert.Equal("PackageInTfm", package2.Id); - Assert.Equal(VersionRange.Parse("0.2.0-beta"), package2.VersionRange); - } - } - - [Fact] - public void WarnIfMissingFilesNodes() - { - var nuspec = CreateNuspec(@" - - - - HasNoFiles - 1.0.0 - Test - Test - - - "); - - var engine = new MockEngine(); - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = engine, - DestinationFolder = _tempDir, - }; - Assert.True(task.Execute()); - var warning = Assert.Single(engine.Warnings); - Assert.Equal("KRB" + KoreBuildErrors.NuspecMissingFilesNode, warning.Code); - } - - [Fact] - public void PacksFiles() - { - var files = new[] - { - Path.Combine("lib", "netstandard1.0", "_._"), - "top.txt", - }; - - var items = new List(); - - foreach (var file in files) - { - var path = Path.Combine(_tempDir, file); - Directory.CreateDirectory(Path.GetDirectoryName(path)); - File.WriteAllText(path, ""); - items.Add(new TaskItem(path, new Hashtable { ["PackagePath"] = file })); - } - - var nuspec = CreateNuspec(@" - - - - HasFiles - 1.0.0 - Test - Test - - - - "); - - var engine = new MockEngine(); - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = engine, - PackageFiles = items.ToArray(), - DestinationFolder = _tempDir, - }; - - Assert.True(task.Execute()); - var result = Assert.Single(task.Packages); - - using (var reader = new PackageArchiveReader(result.ItemSpec)) - { - Assert.Contains("lib/netstandard1.0/_._", reader.GetFiles()); - Assert.Contains("top.txt", reader.GetFiles()); - } - } - - [Theory] - [InlineData("")] - [InlineData("/")] - [InlineData("somedir/")] - public void FailsForBadPackagePath(string path) - { - var nuspec = CreateNuspec(@" - - - - HasFiles - 1.0.0 - Test - Test - - - - "); - - var engine = new MockEngine { ContinueOnError = true }; - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = engine, - PackageFiles = new[] { new TaskItem("file.txt", new Hashtable { ["PackagePath"] = path }) }, - DestinationFolder = _tempDir, - }; - - Assert.False(task.Execute(), "Task should fail"); - var error = Assert.Single(engine.Errors); - Assert.Equal("KRB" + KoreBuildErrors.InvalidPackagePathMetadata, error.Code); - } - - [Fact] - public void SetsLibraryIncludeFlagsOnDependency() - { - var nuspec = CreateNuspec(@" - - - - HasDependencies - 1.0.0 - Test - Test - - - - "); - - var task = new PackNuSpec - { - NuspecPath = nuspec, - BasePath = _tempDir, - BuildEngine = new MockEngine(), - DestinationFolder = _tempDir, - Dependencies = new[] - { - new TaskItem("Include", new Hashtable { ["Version"] = "1.0.0", ["IncludeAssets"] = "Build;Analyzers"}), - new TaskItem("Exclude", new Hashtable { ["Version"] = "1.0.0", ["ExcludeAssets"] = "Compile;Native"}), - new TaskItem("Both", new Hashtable { ["Version"] = "1.0.0", ["IncludeAssets"] = "Build; Analyzers", ["ExcludeAssets"] = "Build; Native; ContentFiles"}), - } - }; - - Assert.True(task.Execute(), "The task should have passed"); - var result = Assert.Single(task.Packages); - - using (var reader = new PackageArchiveReader(result.ItemSpec)) - { - var metadata = new PackageBuilder(reader.GetNuspec(), basePath: null); - var packages = Assert.Single(metadata.DependencyGroups).Packages; - Assert.Equal(3, packages.Count()); - - var include = Assert.Single(packages, p => p.Id == "Include").Include; - Assert.Equal(new[] { "Build", "Analyzers" }, include); - - var exclude = Assert.Single(packages, p => p.Id == "Exclude").Exclude; - Assert.Equal(new[] { "Compile", "Native" }, exclude); - - var both = Assert.Single(packages, p => p.Id == "Both"); - Assert.Equal(new[] { "Build", "Analyzers" }, both.Include); - Assert.Equal(new[] { "Build", "Native", "ContentFiles" }, both.Exclude); - } - } - - [Fact] - public void FailsIfBothOutputPathAndDestinationFolderAreGiven() - { - var engine = new MockEngine { ContinueOnError = true }; - var task = new PackNuSpec - { - BuildEngine = engine, - OutputPath = _tempDir, - DestinationFolder = _tempDir, - NuspecPath = CreateNuspec(""), - }; - - Assert.False(task.Execute(), "Task should fail"); - Assert.Contains("Either DestinationFolder and OutputPath must be specified, but only not both.", engine.Errors.Select(e => e.Message)); - } - - [Fact] - public void FailsIfNeitherOutputPathAndDestinationFolderAreGiven() - { - var engine = new MockEngine { ContinueOnError = true }; - var task = new PackNuSpec - { - BuildEngine = engine, - NuspecPath = CreateNuspec(""), - }; - - Assert.False(task.Execute(), "Task should fail"); - Assert.Contains("Either DestinationFolder and OutputPath must be specified, but only not both.", engine.Errors.Select(e => e.Message)); - } - - private string CreateNuspec(string xml) - { - var nuspecPath = Path.Combine(_tempDir, Path.GetRandomFileName() + ".nuspec"); - File.WriteAllText(nuspecPath, xml.Replace('`', '"').TrimStart()); - return nuspecPath; - } - - public void Dispose() - { - try - { - Directory.Delete(_tempDir, recursive: true); - } - catch - { - Console.WriteLine("Failed to delete " + _tempDir); - } - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/SolutionInfoFactoryTests.cs b/test/KoreBuild.Tasks.Tests/SolutionInfoFactoryTests.cs deleted file mode 100644 index f2eaad004..000000000 --- a/test/KoreBuild.Tasks.Tests/SolutionInfoFactoryTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using KoreBuild.Tasks.ProjectModel; -using Xunit; - -namespace KoreBuild.Tasks.Tests -{ - public class SolutionInfoFactoryTests : IDisposable - { - private readonly string _slnFile; - - public SolutionInfoFactoryTests() - { - _slnFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - } - - [Theory] - [InlineData("", new[] { "ClassLib1", "VsixProject" })] - [InlineData("Debug", new[] { "ClassLib1", "VsixProject" })] - [InlineData("DebugNoVSIX", new[] { "ClassLib1" })] - public void FindsProjectsByDefaultConfiguration(string config, string[] projects) - { - File.WriteAllText(_slnFile, @" -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 -MinimumVisualStudioVersion = 15.0.26124.0 -Project(`{2150E333-8FDC-42A3-9474-1A3956D46DE8}`) = `src`, `src`, `{6BC8A037-601B-412E-B394-92F55C01C7A6}` -EndProject -Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `ClassLib1`, `src\ClassLib1\ClassLib1.csproj`, `{89EF0B05-98D4-4C4D-8870-718571091F79}` -EndProject -Project(`{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}`) = `VsixProject`, `src\VsixProject\VsixProject.csproj`, `{86986537-8DF5-423F-A3A8-0CA568A9FFC4}` -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - DebugNoVSIX|Any CPU = DebugNoVSIX|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {89EF0B05-98D4-4C4D-8870-718571091F79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {89EF0B05-98D4-4C4D-8870-718571091F79}.Debug|Any CPU.Build.0 = Debug|Any CPU - {86986537-8DF5-423F-A3A8-0CA568A9FFC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {86986537-8DF5-423F-A3A8-0CA568A9FFC4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89EF0B05-98D4-4C4D-8870-718571091F79}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - {89EF0B05-98D4-4C4D-8870-718571091F79}.DebugNoVSIX|Any CPU.Build.0 = Debug|Any CPU - {86986537-8DF5-423F-A3A8-0CA568A9FFC4}.DebugNoVSIX|Any CPU.ActiveCfg = Debug|Any CPU - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {89EF0B05-98D4-4C4D-8870-718571091F79} = {6BC8A037-601B-412E-B394-92F55C01C7A6} - {86986537-8DF5-423F-A3A8-0CA568A9FFC4} = {6BC8A037-601B-412E-B394-92F55C01C7A6} - EndGlobalSection -EndGlobal -".Replace('`', '"')); - - var solution = SolutionInfoFactory.Create(_slnFile, config); - Assert.Equal(projects.Length, solution.Projects.Count); - Assert.All(projects, expected => Assert.Contains(solution.Projects, proj => Path.GetFileNameWithoutExtension(proj) == expected)); - } - - [Fact] - public void ThrowsForBadConfigName() - { - File.WriteAllText(_slnFile, @" -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 -MinimumVisualStudioVersion = 15.0.26124.0 -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal -".Replace('`', '"')); - - Assert.Throws(() => SolutionInfoFactory.Create(_slnFile, "Release")); - } - - public void Dispose() - { - try - { - File.Delete(_slnFile); - } - catch { } - } - } -} diff --git a/test/KoreBuild.Tasks.Tests/TestResources/lorem.bin b/test/KoreBuild.Tasks.Tests/TestResources/lorem.bin deleted file mode 100644 index 2408fe952..000000000 --- a/test/KoreBuild.Tasks.Tests/TestResources/lorem.bin +++ /dev/null @@ -1 +0,0 @@ -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque et nulla laoreet ex pharetra congue. Sed gravida justo orci. Nunc nec est vitae purus accumsan consectetur et vel risus. Sed lobortis nulla eu feugiat ornare. Pellentesque ornare semper lorem at vestibulum. Aliquam molestie erat nunc. Curabitur suscipit aliquet quam quis fringilla. diff --git a/test/KoreBuild.Tasks.Tests/UpgradeDependenciesTests.cs b/test/KoreBuild.Tasks.Tests/UpgradeDependenciesTests.cs deleted file mode 100644 index 3de7997f3..000000000 --- a/test/KoreBuild.Tasks.Tests/UpgradeDependenciesTests.cs +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Threading.Tasks; -using BuildTools.Tasks.Tests; -using KoreBuild.Tasks.Utilities; -using Microsoft.Build.Construction; -using Microsoft.Build.Evaluation; -using NuGet.Packaging; -using NuGet.Packaging.Core; -using NuGet.Versioning; -using Xunit; -using Xunit.Abstractions; - -namespace KoreBuild.Tasks.Tests -{ - [Collection(nameof(MSBuildTestCollection))] - public class UpgradeDependenciesTests : IDisposable - { - private readonly string _tempDir; - private readonly ITestOutputHelper _output; - - public UpgradeDependenciesTests(ITestOutputHelper output, MSBuildTestCollectionFixture fixture) - { - fixture.InitializeEnvironment(output); - _tempDir = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName()); - Directory.CreateDirectory(_tempDir); - _output = output; - } - - [Fact] - public async Task WarnsWhenVariableIsNotInPackage() - { - // arrange - var packageId = new PackageIdentity("Lineup", NuGetVersion.Parse("1.0.0")); - var lineupPackagePath = CreateLineup(packageId); - var depsFilePath = CreateProjectDepsFile(new VersionVariable("PackageVersionVar", "1.0.0")); - var engine = new MockEngine(_output); - - // act - var task = new UpgradeDependencies - { - BuildEngine = engine, - DependenciesFile = depsFilePath, - LineupPackageId = packageId.Id, - LineupPackageRestoreSource = _tempDir, - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - var warning = Assert.Single(engine.Warnings); - Assert.Equal(KoreBuildErrors.Prefix + KoreBuildErrors.PackageVersionNotFoundInLineup, warning.Code); - - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal("1.0.0", modifiedDepsFile.VersionVariables["PackageVersionVar"].Version); - } - - [Fact] - public async Task ModifiesVariableValue() - { - // arrange - var packageId = new PackageIdentity("Lineup", NuGetVersion.Parse("1.0.0")); - var lineupPackagePath = CreateLineup(packageId, new VersionVariable("PackageVersionVar", "2.0.0")); - var depsFilePath = CreateProjectDepsFile(new VersionVariable("PackageVersionVar", "1.0.0")); - - // act - var task = new UpgradeDependencies - { - BuildEngine = new MockEngine(_output), - DependenciesFile = depsFilePath, - LineupPackageId = packageId.Id, - LineupPackageRestoreSource = _tempDir, - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal("2.0.0", modifiedDepsFile.VersionVariables["PackageVersionVar"].Version); - Assert.False(modifiedDepsFile.VersionVariables["PackageVersionVar"].IsReadOnly); - } - - - [Fact] - public async Task DoesNotModifyPinnedVariableValue() - { - // arrange - var packageId = new PackageIdentity("Lineup", NuGetVersion.Parse("1.0.0")); - var lineupPackagePath = CreateLineup(packageId, new VersionVariable("PackageVersionVar", "2.0.0")); - var depsFilePath = CreateProjectDepsFile(new VersionVariable("PackageVersionVar", "1.0.0") { IsReadOnly = true }); - - // act - var task = new UpgradeDependencies - { - BuildEngine = new MockEngine(_output), - DependenciesFile = depsFilePath, - LineupPackageId = packageId.Id, - LineupPackageRestoreSource = _tempDir, - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - _output.WriteLine(File.ReadAllText(depsFilePath)); - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal("1.0.0", modifiedDepsFile.VersionVariables["PackageVersionVar"].Version); - Assert.True(modifiedDepsFile.VersionVariables["PackageVersionVar"].IsReadOnly); - } - - - [Fact] - public async Task ModifiesVariableValueUsingDepsFile() - { - // arrange - var depsFilePath = CreateProjectDepsFile(new VersionVariable("PackageVersionVar", "1.0.0")); - var updatedDepsFilePath = CreateProjectDepsFile(Path.Combine(_tempDir, "dependencies.props"), new VersionVariable("PackageVersionVar", "2.0.0")); - - // act - var task = new UpgradeDependencies - { - BuildEngine = new MockEngine(_output), - DependenciesFile = depsFilePath, - LineupDependenciesFile = updatedDepsFilePath - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal("2.0.0", modifiedDepsFile.VersionVariables["PackageVersionVar"].Version); - } - - [Fact] - public async Task SnapsInternalAspNetCoreSdkToBuildTools() - { - // arrange - var packageId = new PackageIdentity("Lineup", NuGetVersion.Parse("1.0.0")); - var lineupPackagePath = CreateLineup(packageId, new VersionVariable("InternalAspNetCoreSdkPackageVersion", "2.0.0")); - var depsFilePath = CreateProjectDepsFile(new VersionVariable("InternalAspNetCoreSdkPackageVersion", "1.0.0")); - - // act - var task = new UpgradeDependencies - { - BuildEngine = new MockEngine(_output), - DependenciesFile = depsFilePath, - LineupPackageId = packageId.Id, - LineupPackageRestoreSource = _tempDir, - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal(KoreBuildVersion.Current, modifiedDepsFile.VersionVariables["InternalAspNetCoreSdkPackageVersion"].Version); - } - - [Fact] - public async Task DoesNotModifiesFileIfNoChanges() - { - // arrange - var packageId = new PackageIdentity("Lineup", NuGetVersion.Parse("1.0.0")); - var pkg = new VersionVariable("PackageVersionVar", "1.0.0"); - var lineupPackagePath = CreateLineup(packageId, pkg); - var depsFilePath = CreateProjectDepsFile(pkg); - var created = File.GetLastWriteTime(depsFilePath); - - // act - var task = new UpgradeDependencies - { - BuildEngine = new MockEngine(_output), - DependenciesFile = depsFilePath, - LineupPackageId = packageId.Id, - LineupPackageRestoreSource = _tempDir, - }; - - // assert - Assert.True(await task.ExecuteAsync(), "Task is expected to pass"); - var modifiedDepsFile = DependencyVersionsFile.Load(depsFilePath); - Assert.Equal("1.0.0", modifiedDepsFile.VersionVariables["PackageVersionVar"].Version); - Assert.Equal(created, File.GetLastWriteTime(depsFilePath)); - } - - private string CreateProjectDepsFile(params VersionVariable[] variables) - { - return CreateProjectDepsFile(Path.Combine(_tempDir, "projectdeps.props"), variables); - } - - private string CreateProjectDepsFile(string depsFilePath, params VersionVariable[] variables) - { - var proj = ProjectRootElement.Create(NewProjectFileOptions.None); - var originalDepsFile = DependencyVersionsFile.Load(proj); - foreach (var item in variables) - { - if (item.IsReadOnly) - { - originalDepsFile.AddPinnedVariable(item.Name, item.Version); - } - else - { - originalDepsFile.Update(item.Name, item.Version); - } - } - originalDepsFile.Save(depsFilePath); - return depsFilePath; - } - - private string CreateLineup(PackageIdentity identity, params VersionVariable[] variables) - { - var output = Path.Combine(_tempDir, $"{identity.Id}.{identity.Version}.nupkg"); - - var proj = ProjectRootElement.Create(NewProjectFileOptions.None); - var depsFiles = DependencyVersionsFile.Load(proj); - foreach (var item in variables) - { - depsFiles.Update(item.Name, item.Version); - } - depsFiles.Save(Path.Combine(_tempDir, "dependencies.props")); - - var builder = new PackageBuilder - { - Id = identity.Id, - Version = identity.Version, - Owners = { "Test" }, - Authors = { "Test" }, - Description = "Test lineup package" - }; - - builder.AddFiles(_tempDir, "dependencies.props", "build/dependencies.props"); - - using (var stream = File.Create(output)) - { - builder.Save(stream); - } - - return output; - } - - public void Dispose() - { - Directory.Delete(_tempDir, recursive: true); - } - - private struct VersionVariable - { - public string Name; - public string Version; - internal bool IsReadOnly; - - public VersionVariable(string varName, string version) : this() - { - this.Name = varName; - this.Version = version; - } - } - } -} diff --git a/testassets/RepoThatShouldFailToBuild/korebuild.json b/testassets/RepoThatShouldFailToBuild/korebuild.json index 8a276a7f3..2d2c95708 100644 --- a/testassets/RepoThatShouldFailToBuild/korebuild.json +++ b/testassets/RepoThatShouldFailToBuild/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "master" + "channel": "feature/vs2019" } diff --git a/testassets/RepoThatShouldFailToBuild/src/BadConsole/BadConsole.csproj b/testassets/RepoThatShouldFailToBuild/src/BadConsole/BadConsole.csproj index 497bf8488..958d2f1da 100644 --- a/testassets/RepoThatShouldFailToBuild/src/BadConsole/BadConsole.csproj +++ b/testassets/RepoThatShouldFailToBuild/src/BadConsole/BadConsole.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/testassets/RepoWithGlobalTool/korebuild.json b/testassets/RepoWithGlobalTool/korebuild.json index 8a276a7f3..2d2c95708 100644 --- a/testassets/RepoWithGlobalTool/korebuild.json +++ b/testassets/RepoWithGlobalTool/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "master" + "channel": "feature/vs2019" } diff --git a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj b/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj index 06d3435d3..bd90560e4 100644 --- a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj +++ b/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj @@ -1,4 +1,4 @@ - + Exe diff --git a/testassets/SimpleRepo/Directory.Build.props b/testassets/SimpleRepo/Directory.Build.props index 49ef3296a..31b0d1447 100644 --- a/testassets/SimpleRepo/Directory.Build.props +++ b/testassets/SimpleRepo/Directory.Build.props @@ -1,5 +1,8 @@ - + + + true + diff --git a/testassets/SimpleRepo/build/Sample.Lineup.nuspec b/testassets/SimpleRepo/build/Sample.Lineup.nuspec deleted file mode 100644 index 9dc148902..000000000 --- a/testassets/SimpleRepo/build/Sample.Lineup.nuspec +++ /dev/null @@ -1,15 +0,0 @@ - - - - Sample.Lineup - $version$ - KoreBuild - Description. - - - - - - - - diff --git a/testassets/SimpleRepo/build/repo.targets b/testassets/SimpleRepo/build/repo.targets index c7f3af77e..6971488f7 100644 --- a/testassets/SimpleRepo/build/repo.targets +++ b/testassets/SimpleRepo/build/repo.targets @@ -1,27 +1,9 @@ $(PrepareDependsOn);Greet - $(PackageDependsOn);PackLineup - $(VerifyDependsOn);TestNuGetPush;UpgradeDependencies - - Sample.Lineup - $(Version) - $(IntermediateDir) - - - - - - - - - - - - diff --git a/testassets/SimpleRepo/build/sources.props b/testassets/SimpleRepo/build/sources.props deleted file mode 100644 index a5c9ae8bc..000000000 --- a/testassets/SimpleRepo/build/sources.props +++ /dev/null @@ -1,5 +0,0 @@ - - - $(RestoreAdditionalProjectSources);$(KoreBuildBundledPackageFolder) - - diff --git a/testassets/SimpleRepo/build/tasks/RepoTasks.csproj b/testassets/SimpleRepo/build/tasks/RepoTasks.csproj index cdea37999..5567856ce 100644 --- a/testassets/SimpleRepo/build/tasks/RepoTasks.csproj +++ b/testassets/SimpleRepo/build/tasks/RepoTasks.csproj @@ -1,8 +1,9 @@ - + + netcoreapp3.0 - RepoTasks + diff --git a/testassets/SimpleRepo/korebuild.json b/testassets/SimpleRepo/korebuild.json index 8a276a7f3..2d2c95708 100644 --- a/testassets/SimpleRepo/korebuild.json +++ b/testassets/SimpleRepo/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "master" + "channel": "feature/vs2019" } diff --git a/testassets/SimpleRepo/samples/Simple.Sample/Simple.Sample.csproj b/testassets/SimpleRepo/samples/Simple.Sample/Simple.Sample.csproj index 852793c1f..e289a325d 100644 --- a/testassets/SimpleRepo/samples/Simple.Sample/Simple.Sample.csproj +++ b/testassets/SimpleRepo/samples/Simple.Sample/Simple.Sample.csproj @@ -1,4 +1,4 @@ - + diff --git a/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj b/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj index 8de1419f3..4a9b18dab 100644 --- a/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj +++ b/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj @@ -1,4 +1,4 @@ - + netcoreapp3.0 @@ -7,7 +7,7 @@ cowsay Simple.CliTool true - win-x64;win-x86 + TestCert MyPackageSigningCert diff --git a/testassets/SimpleRepo/src/Simple.Lib/Simple.Lib.csproj b/testassets/SimpleRepo/src/Simple.Lib/Simple.Lib.csproj index 90776f448..cb7605251 100644 --- a/testassets/SimpleRepo/src/Simple.Lib/Simple.Lib.csproj +++ b/testassets/SimpleRepo/src/Simple.Lib/Simple.Lib.csproj @@ -1,8 +1,9 @@ - + netstandard2.0;net461 TestCert + NuGet diff --git a/testassets/SimpleRepo/test/Simple.Test/Simple.Test.csproj b/testassets/SimpleRepo/test/Simple.Test/Simple.Test.csproj index f68591deb..114e37ba1 100644 --- a/testassets/SimpleRepo/test/Simple.Test/Simple.Test.csproj +++ b/testassets/SimpleRepo/test/Simple.Test/Simple.Test.csproj @@ -1,4 +1,4 @@ - + netcoreapp3.0;net461 diff --git a/tools/KoreBuild.Console/Commands/ApiBaselinesGenerateCommand.cs b/tools/KoreBuild.Console/Commands/ApiBaselinesGenerateCommand.cs deleted file mode 100644 index e1bb37c57..000000000 --- a/tools/KoreBuild.Console/Commands/ApiBaselinesGenerateCommand.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class ApiBaselinesGenerateCommand : SubCommandBase - { - public ApiBaselinesGenerateCommand(CommandContext context) : base(context) - { - } - - public override void Configure(CommandLineApplication application) - { - application.Description = "Generates baselines for all projects in this repo."; - - base.Configure(application); - } - - protected override int Execute() - { - var args = new List - { - "msbuild", - "/nologo", - "/m", - $"/p:KoreBuildVersion={this.Context.KoreBuildVersion}", - $"/p:RepositoryRoot=\"{this.Context.RepoPath}/\"", - "\"/p:GenerateBaselines=true\"", - "\"/p:SkipTests=true\"", - "/clp:Summary", - Path.Combine(Context.KoreBuildDir, "KoreBuild.proj") - }; - - if (Reporter.IsVerbose) - { - args.Add("\"/v:n\""); - } - else - { - args.Add("\"/v:m\""); - } - - return RunDotnet(args, Context.RepoPath); - } - } -} diff --git a/tools/KoreBuild.Console/Commands/CommandBase.cs b/tools/KoreBuild.Console/Commands/CommandBase.cs deleted file mode 100644 index bb8fcc8c9..000000000 --- a/tools/KoreBuild.Console/Commands/CommandBase.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal abstract class CommandBase - { - private CommandLineApplication _application; - - public virtual void Configure(CommandLineApplication application) - { - _application = application; - - application.HelpOption("-h|--help"); - - application.OnExecute( - () => - { - if (IsValid()) - { - return Execute(); - } - else - { - application.ShowHelp(); - return 1; - } - }); - } - - protected virtual int Execute() - { - _application.ShowHelp(); - - return 0; - } - - protected virtual bool IsValid() - { - return true; - } - } -} diff --git a/tools/KoreBuild.Console/Commands/CommandContext.cs b/tools/KoreBuild.Console/Commands/CommandContext.cs deleted file mode 100644 index 2373311c8..000000000 --- a/tools/KoreBuild.Console/Commands/CommandContext.cs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using Microsoft.Extensions.CommandLineUtils; -using Microsoft.Extensions.Tools.Internal; - -namespace KoreBuild.Console.Commands -{ - internal class CommandContext - { - private const string _defaultToolsSource = "https://aspnetcore.blob.core.windows.net/buildtools"; - private const string _dotnetFolderName = ".dotnet"; - - private CommandOption _repoPathOption; - private CommandOption _dotNetHomeOption; - private CommandOption _toolsSourceOption; - private CommandOption _verbose; - - private string _koreBuildDir; - private CommandOption _korebuildOverrideOpt; - - public CommandContext(CommandLineApplication application) - { - _korebuildOverrideOpt = application.Option("--korebuild-override ", "Where is KoreBuild?", CommandOptionType.SingleValue, inherited: true); - // for local development only - _korebuildOverrideOpt.ShowInHelpText = false; - - _verbose = application.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue, inherited: true); - _toolsSourceOption = application.Option("--tools-source", "The source to draw tools from.", CommandOptionType.SingleValue, inherited: true); - _repoPathOption = application.Option("--repo-path", "The path to the repo to work on.", CommandOptionType.SingleValue, inherited: true); - _dotNetHomeOption = application.Option("--dotnet-home", "The place where dotnet lives", CommandOptionType.SingleValue, inherited: true); - // TODO: Configure file - } - - public string KoreBuildDir - { - get - { - if (_koreBuildDir == null) - { - _koreBuildDir = FindKoreBuildDirectory(); - } - return _koreBuildDir; - } - } - - public string ConfigDirectory => Path.Combine(KoreBuildDir, "config"); - public string RepoPath => _repoPathOption.HasValue() ? _repoPathOption.Value() : Directory.GetCurrentDirectory(); - public string DotNetHome => GetDotNetHome(); - public string ToolsSource => _toolsSourceOption.HasValue() ? _toolsSourceOption.Value() : _defaultToolsSource; - public string SDKVersion => GetDotnetSDKVersion(); - - public string KoreBuildVersion => GetKoreBuildVersion(); - - public IReporter Reporter => new ConsoleReporter(PhysicalConsole.Singleton, _verbose != null, false); - - private string GetDotnetSDKVersion() - { - var sdkVersionEnv = Environment.GetEnvironmentVariable("KOREBUILD_DOTNET_VERSION"); - if (sdkVersionEnv != null) - { - return sdkVersionEnv; - } - else - { - var sdkVersionPath = Path.Combine(ConfigDirectory, "sdk.version"); - return File.ReadAllText(sdkVersionPath).Trim(); - } - } - - private string GetDotNetHome() - { - var dotnetHome = Environment.GetEnvironmentVariable("DOTNET_HOME"); - var userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); - var home = Environment.GetEnvironmentVariable("HOME"); - - var result = Path.Combine(Directory.GetCurrentDirectory(), _dotnetFolderName); - if (_dotNetHomeOption.HasValue()) - { - result = _dotNetHomeOption.Value(); - } - else if (!string.IsNullOrEmpty(dotnetHome)) - { - result = dotnetHome; - } - else if (!string.IsNullOrEmpty(userProfile)) - { - result = Path.Combine(userProfile, _dotnetFolderName); - } - else if (!string.IsNullOrEmpty(home)) - { - result = home; - } - - return result; - } - - private string GetKoreBuildVersion() - { - var dir = new DirectoryInfo(FindKoreBuildDirectory()); - return dir.Parent.Name; - } - - private string FindKoreBuildDirectory() - { - if (_korebuildOverrideOpt.HasValue()) - { - return Path.GetFullPath(_korebuildOverrideOpt.Value()); - } - - var executingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - var root = Directory.GetDirectoryRoot(executingDir); - while (executingDir != root) - { - var files = Directory.EnumerateFiles(executingDir); - var koreProj = Path.Combine(executingDir, "KoreBuild.proj"); - if (files.Contains(koreProj)) - { - return executingDir; - } - - var directories = Directory.EnumerateDirectories(executingDir); - - var fileDir = Path.Combine(executingDir, "files"); - if (directories.Contains(fileDir)) - { - return Path.Combine(fileDir, "KoreBuild"); - } - - executingDir = Directory.GetParent(executingDir).FullName; - } - - Reporter.Error("Couldn't find the KoreBuild directory."); - throw new DirectoryNotFoundException(); - } - - public string GetDotNetInstallDir() - { - var dotnetDir = DotNetHome; - if (IsWindows()) - { - dotnetDir = Path.Combine(dotnetDir, GetArchitecture()); - } - - return dotnetDir; - } - - public string GetDotNetExecutable() - { - var dotnetDir = GetDotNetInstallDir(); - - var dotnetFile = "dotnet"; - - if (IsWindows()) - { - dotnetFile += ".exe"; - } - - return Path.Combine(dotnetDir, dotnetFile); - } - - public string GetArchitecture() - { - return Environment.GetEnvironmentVariable("KOREBUILD_DOTNET_ARCH") ?? "x64"; - } - - public bool IsWindows() - { - return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - } - } -} diff --git a/tools/KoreBuild.Console/Commands/DependenciesGenerateCommand.cs b/tools/KoreBuild.Console/Commands/DependenciesGenerateCommand.cs deleted file mode 100644 index 274de1c7f..000000000 --- a/tools/KoreBuild.Console/Commands/DependenciesGenerateCommand.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class DependenciesGenerateCommand : SubCommandBase - { - private CommandOption _configOpt; - private CommandOption _fileOpt; - - public DependenciesGenerateCommand(CommandContext context) : base(context) - { - } - - public override void Configure(CommandLineApplication application) - { - application.Description = "Generates a build/dependencies.props file and updates csproj files to use variables"; - application.ExtendedHelpText = @" -MORE INFO: - - This command will generate a dependencies.props file and adjust all PackageReference's in csproj files - to use the MSBuild variables it generates. - - Example output: - - - - 1.0.0 - - -"; - - _configOpt = application.Option("-c|--configuration ", "The MSBuild configuration. Defaults to 'Debug'.", CommandOptionType.SingleValue); - _fileOpt = application.Option("--deps-file ", "The dependencies.props file to upgrade.", CommandOptionType.SingleValue); - - base.Configure(application); - } - - protected override int Execute() - { - var args = new List - { - "msbuild", - Path.Combine(Context.KoreBuildDir, "KoreBuild.proj"), - "-t:GenerateDependenciesPropsFile", - }; - - if (_configOpt.HasValue()) - { - args.Add("-p:Configuration=" + _configOpt.Value()); - } - - if (_fileOpt.HasValue()) - { - var filePath = _fileOpt.Value(); - if (!Path.IsPathRooted(filePath)) - { - filePath = Path.GetFullPath(filePath); - } - - args.Add("-p:DependencyVersionsFile=" + filePath); - } - - if (Reporter.IsVerbose) - { - args.Add("-v:n"); - } - - return RunDotnet(args, Context.RepoPath); - } - } -} diff --git a/tools/KoreBuild.Console/Commands/DependenciesUpgradeCommand.cs b/tools/KoreBuild.Console/Commands/DependenciesUpgradeCommand.cs deleted file mode 100644 index b830e71a5..000000000 --- a/tools/KoreBuild.Console/Commands/DependenciesUpgradeCommand.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class DependenciesUpgradeCommand : SubCommandBase - { - private CommandOption _sourceOpt; - private CommandOption _packageIdOpt; - private CommandOption _packageVersionOpt; - private CommandOption _sourceDeps; - private CommandOption _fileOpt; - - public DependenciesUpgradeCommand(CommandContext context) : base(context) - { - } - - public override void Configure(CommandLineApplication application) - { - application.Description = "Upgrades the build/dependencies.props file to the latest package versions"; - application.ExtendedHelpText = @" -MORE INFO: - - The upgrade uses a 'lineup' package as the source of information about which versions to use. - - A lineup package is simply a nuget package that contains a file in build/dependencies.props. - Just like the version of the file in this local repo, this file is an MSBuild project file - with a list of MSBuild variables. Example: - - - - 1.0.0 - - -"; - - _sourceOpt = application.Option("-s|--source ", - "Specifies a NuGet package source to use to upgrade dependencies to the latest lineup package.", CommandOptionType.SingleValue); - _packageIdOpt = application.Option("--id ", "Specifies the lineup package id to use.", CommandOptionType.SingleValue); - _packageVersionOpt = application.Option("--version ", "Specifies the lineup package version to use.", CommandOptionType.SingleValue); - _sourceDeps = application.Option("--source-deps ", "The dependencies.props file to use as a source of versions.", CommandOptionType.SingleValue); - _fileOpt = application.Option("--deps-file ", "The dependencies.props file to upgrade.", CommandOptionType.SingleValue); - - base.Configure(application); - } - - protected override int Execute() - { - var args = new List - { - "msbuild", - Path.Combine(Context.KoreBuildDir, "KoreBuild.proj"), - "-t:UpgradeDependencies", - }; - - if (_sourceOpt.HasValue()) - { - args.Add("-p:LineupPackageRestoreSource=" + _sourceOpt.Value()); - } - - if (_packageIdOpt.HasValue()) - { - args.Add("-p:LineupPackageId=" + _packageIdOpt.Value()); - } - - if (_packageVersionOpt.HasValue()) - { - args.Add("-p:LineupPackageVersion=" + _packageVersionOpt.Value()); - } - - if (_sourceDeps.HasValue()) - { - args.Add("-p:LineupDependenciesFile=" + _sourceDeps.Value()); - } - - if (_fileOpt.HasValue()) - { - var filePath = _fileOpt.Value(); - if (!Path.IsPathRooted(filePath)) - { - filePath = Path.GetFullPath(filePath); - } - - args.Add("-p:DependencyVersionsFile=" + filePath); - } - - if (Reporter.IsVerbose) - { - args.Add("-v:n"); - } - - return RunDotnet(args, Context.RepoPath); - } - } -} diff --git a/tools/KoreBuild.Console/Commands/DockerBuildCommand.cs b/tools/KoreBuild.Console/Commands/DockerBuildCommand.cs deleted file mode 100644 index 7e8e8eb9f..000000000 --- a/tools/KoreBuild.Console/Commands/DockerBuildCommand.cs +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class DockerBuildCommand : SubCommandBase - { - private const string DockerIgnore = ".dockerignore"; - private const string DockerfileExtension = ".dockerfile"; - private const string Owner = "aspnetbuild"; - private const string ImageName = "korebuild"; - - public DockerBuildCommand(CommandContext context) : base(context) - { - } - - public CommandArgument ImageVariant { get; set; } - - public List Arguments { get; set; } - - public string Tag => $@"{Owner}/{ImageName}:{ImageVariant.Value}"; - - public override void Configure(CommandLineApplication application) - { - ImageVariant = application.Argument("image", "The docker image to run on."); - Arguments = application.RemainingArguments; - - base.Configure(application); - } - - protected override bool IsValid() - { - if (string.IsNullOrEmpty(ImageVariant?.Value)) - { - Reporter.Error("Image is a required argument."); - return false; - } - - return true; - } - - protected override int Execute() - { - var dockerFileName = GetDockerFileName(ImageVariant.Value); - var dockerFileSource = GetDockerFileSource(dockerFileName); - var dockerFileDestination = Path.Combine(Context.RepoPath, GetDockerFileName(ImageVariant.Value)); - - File.Copy(dockerFileSource, dockerFileDestination, overwrite: true); - - var dockerIgnoreSource = GetDockerFileSource(DockerIgnore); - var dockerIgnoreDestination = Path.Combine(Context.RepoPath, DockerIgnore); - - File.Copy(dockerIgnoreSource, dockerIgnoreDestination, overwrite: true); - - // If our ToolSource isn't http copy it to the docker context - var dockerToolsSource = Context.ToolsSource; - string toolsSourceDestination = null; - if (!Context.ToolsSource.StartsWith("http")) - { - dockerToolsSource = "ToolsSource"; - toolsSourceDestination = Path.Combine(Context.RepoPath, dockerToolsSource); - DirectoryCopy(Context.ToolsSource, toolsSourceDestination); - } - - try - { - var buildArgs = new List { "build" }; - - buildArgs.AddRange(new string[] { "-t", Tag, "-f", dockerFileDestination, Context.RepoPath }); - var buildResult = RunDockerCommand(buildArgs); - - if (buildResult != 0) - { - return buildResult; - } - - var containerName = $"{Owner}_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; - - var runArgs = new List { "run", "--rm", "-i", "--name", containerName, Tag }; - - runArgs.AddRange(new[] { "-ToolsSource", dockerToolsSource }); - - if (Arguments?.Count > 0) - { - runArgs.AddRange(Arguments); - } - - Reporter.Verbose($"Running in container '{containerName}'"); - return RunDockerCommand(runArgs); - } - finally - { - // Clean up the stuff we dumped there in order to get it in the docker context. - File.Delete(dockerFileDestination); - File.Delete(dockerIgnoreDestination); - if (toolsSourceDestination != null) - { - Directory.Delete(toolsSourceDestination, recursive: true); - } - } - } - - private string GetDockerFileSource(string fileName) - { - var executingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - var source = Path.Combine(executingDir, "Commands", "DockerFiles", fileName); - - if (!File.Exists(source)) - { - Reporter.Error($"DockerFile '{source}' doesn't exist."); - throw new FileNotFoundException(); - } - - return source; - } - - private string GetDockerFileName(string platform) - { - return $"{platform}{DockerfileExtension}"; - } - - private int RunDockerCommand(List arguments) - { - var args = ArgumentEscaper.EscapeAndConcatenate(arguments.ToArray()); - Reporter.Verbose($"Running 'docker {args}'"); - - var psi = new ProcessStartInfo - { - FileName = "docker", - Arguments = args, - RedirectStandardError = true - }; - - var process = Process.Start(psi); - process.WaitForExit(); - - if (process.ExitCode != 0) - { - Reporter.Error(process.StandardError.ReadToEnd()); - } - - return process.ExitCode; - } - - private static void DirectoryCopy(string sourceDirName, string destDirName) - { - // 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, overwrite: true); - } - - // Copy subdirectories and their contents to the new location. - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - DirectoryCopy(subdir.FullName, temppath); - } - } - } -} diff --git a/tools/KoreBuild.Console/Commands/DockerFiles/.dockerignore b/tools/KoreBuild.Console/Commands/DockerFiles/.dockerignore deleted file mode 100644 index 26f97c87a..000000000 --- a/tools/KoreBuild.Console/Commands/DockerFiles/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -korebuild-lock.txt -**/bin -**/obj -artifacts diff --git a/tools/KoreBuild.Console/Commands/DockerFiles/jessie.dockerfile b/tools/KoreBuild.Console/Commands/DockerFiles/jessie.dockerfile deleted file mode 100644 index cef20b92f..000000000 --- a/tools/KoreBuild.Console/Commands/DockerFiles/jessie.dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM microsoft/dotnet:2.0-runtime-deps-jessie - -RUN apt-get update \ - && apt-get install -y --no-install-recommends \ - git \ - # KoreBuild dependencies - jq \ - curl \ - unzip \ - apt-transport-https \ - && rm -rf /var/lib/apt/lists/* - -ADD . . - -ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true - -RUN ./run.sh install-tools - -ENTRYPOINT ["./build.sh"] diff --git a/tools/KoreBuild.Console/Commands/DockerFiles/winservercore.dockerfile b/tools/KoreBuild.Console/Commands/DockerFiles/winservercore.dockerfile deleted file mode 100644 index a591f1adf..000000000 --- a/tools/KoreBuild.Console/Commands/DockerFiles/winservercore.dockerfile +++ /dev/null @@ -1,20 +0,0 @@ -FROM microsoft/aspnet:4.6.2 - - -# DevPack returns exit 0 immediately, but it's not done, so we wait. -# A more correct thing would be to block on a registry key existing or similar. -RUN \ - Invoke-WebRequest https://download.microsoft.com/download/F/1/D/F1DEB8DB-D277-4EF9-9F48-3A65D4D8F965/NDP461-DevPack-KB3105179-ENU.exe -OutFile ~\\net461dev.exe ; \ - ~\\net461dev.exe /Passive /NoRestart ; \ - Start-Sleep -s 10; \ - Remove-Item ~\\net461dev.exe -Force ; - -WORKDIR c:\\repo - -ADD . . - -ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE=true - -RUN ./run.ps1 install-tools - -ENTRYPOINT ["build.cmd"] diff --git a/tools/KoreBuild.Console/Commands/InstallToolsCommand.cs b/tools/KoreBuild.Console/Commands/InstallToolsCommand.cs deleted file mode 100644 index 619065795..000000000 --- a/tools/KoreBuild.Console/Commands/InstallToolsCommand.cs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class InstallToolsCommand : SubCommandBase - { - public InstallToolsCommand(CommandContext context) : base(context) - { - } - - private string KoreBuildSkipRuntimeInstall => Environment.GetEnvironmentVariable("KOREBUILD_SKIP_RUNTIME_INSTALL"); - private string PathENV => Environment.GetEnvironmentVariable("PATH"); - private string DotNetInstallDir => Environment.GetEnvironmentVariable("DOTNET_INSTALL_DIR"); - - public override void Configure(CommandLineApplication application) - { - base.Configure(application); - } - - protected override int Execute() - { - var installDir = Context.GetDotNetInstallDir(); - - Reporter.Verbose($"Installing tools to '{installDir}'"); - - if (DotNetInstallDir != null && DotNetInstallDir != installDir) - { - Reporter.Verbose($"installDir = {installDir}"); - Reporter.Verbose($"DOTNET_INSTALL_DIR = {DotNetInstallDir}"); - Reporter.Verbose("The environment variable DOTNET_INSTALL_DIR is deprecated. The recommended alternative is DOTNET_HOME."); - } - - var dotnet = Context.GetDotNetExecutable(); - var dotnetOnPath = GetCommandFromPath("dotnet"); - - // TODO: decide case sensitivity and handly symbolic links - if (dotnetOnPath != null && (dotnetOnPath != dotnet)) - { - Reporter.Warn($"dotnet found on the system PATH is '{dotnetOnPath}' but KoreBuild will use '{dotnet}'"); - } - - var pathPrefix = Directory.GetParent(dotnet); - if (PathENV.StartsWith($"{pathPrefix}{Path.PathSeparator}", StringComparison.OrdinalIgnoreCase)) - { - Reporter.Output($"Adding {pathPrefix} to PATH"); - Environment.SetEnvironmentVariable("PATH", $"{pathPrefix};{PathENV}"); - } - - if (KoreBuildSkipRuntimeInstall == "1") - { - Reporter.Output("Skipping runtime installation because KOREBUILD_SKIP_RUNTIME_INSTALL = 1"); - return 0; - } - - var scriptExtension = Context.IsWindows() ? "ps1" : "sh"; - - var scriptPath = Path.Combine(Context.KoreBuildDir, "dotnet-install." + scriptExtension); - - if (!Context.IsWindows()) - { - var args = ArgumentEscaper.EscapeAndConcatenate(new string[] { "+x", scriptPath }); - var psi = new ProcessStartInfo - { - FileName = "chmod", - Arguments = args - }; - - var process = Process.Start(psi); - process.WaitForExit(); - } - - var architecture = Context.GetArchitecture(); - - InstallCLI(scriptPath, installDir, architecture, Context.SDKVersion); - - return 0; - } - - private void InstallCLI(string script, string installDir, string architecture, string version) - { - var sdkPath = Path.Combine(installDir, "sdk", version, "dotnet.dll"); - - if (!File.Exists(sdkPath)) - { - Reporter.Verbose($"Installing dotnet {version} to {installDir}"); - - var args = ArgumentEscaper.EscapeAndConcatenate(new string[] { - "-Version", version, - "-Architecture", architecture, - "-InstallDir", installDir, - // workaround for https://github.com/dotnet/cli/issues/9143 - // disable the CDN, which has non-deterministic behavior when multiple builds of the same SDK version exist - "-NoCdn", - }); - - var psi = new ProcessStartInfo - { - FileName = script, - Arguments = args - }; - - var process = Process.Start(psi); - process.WaitForExit(); - } - else - { - Reporter.Output($".NET Core SDK {version} is already installed. Skipping installation."); - } - } - - private static string GetCommandFromPath(string command) - { - var values = Environment.GetEnvironmentVariable("PATH"); - foreach (var path in values.Split(';')) - { - var fullPath = Path.Combine(path, command); - if (File.Exists(fullPath)) - return fullPath; - } - return null; - } - } -} diff --git a/tools/KoreBuild.Console/Commands/InstallToolsetsCommand.cs b/tools/KoreBuild.Console/Commands/InstallToolsetsCommand.cs deleted file mode 100644 index 4494b917c..000000000 --- a/tools/KoreBuild.Console/Commands/InstallToolsetsCommand.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class InstallToolsetsCommand : SubCommandBase - { - private CommandOption _quietOpt; - private CommandOption _productOpt; - private CommandOption _upgradeOpt; - - public InstallToolsetsCommand(CommandContext context) : base(context) - { - } - - public override void Configure(CommandLineApplication application) - { - application.Description = "Installs the toolsets necessary to build the current project."; - application.ExtendedHelpText = @" -MORE INFO: - - Uses the toolsets specified in korebuild.json to install all toolsets. -"; - _quietOpt = application.Option("-q|--quiet", - "Install toolsets without requiring user interation.", - CommandOptionType.NoValue); - _productOpt = application.Option("--product ", - "Which vs product version to install. Valid values are Enterprise, Professional, or Community.", - CommandOptionType.SingleValue); - _upgradeOpt = application.Option("-u|--upgrade", - "Upgrade existing toolsets.", - CommandOptionType.NoValue); - base.Configure(application); - } - - protected override int Execute() - { - var args = new List - { - "msbuild", - Path.Combine(Context.KoreBuildDir, "KoreBuild.proj"), - "-t:InstallToolsets", - }; - - if (_upgradeOpt.HasValue()) - { - args.Add("-p:UpgradeVSInstallation=true"); - } - - if (_quietOpt.HasValue()) - { - args.Add("-p:QuietVSInstallation=true"); - } - - if (_productOpt.HasValue()) - { - args.Add($"-p:VSProductVersionType={_productOpt.Value()}"); - } - - if (Reporter.IsVerbose) - { - args.Add("-v:n"); - } - - Reporter.Verbose($"Starting msbuild with arguments: {ArgumentEscaper.EscapeAndConcatenate(args)}"); - - return RunDotnet(args, Context.RepoPath); - } - } -} diff --git a/tools/KoreBuild.Console/Commands/MSBuildCommand.cs b/tools/KoreBuild.Console/Commands/MSBuildCommand.cs deleted file mode 100644 index 1ab4c4414..000000000 --- a/tools/KoreBuild.Console/Commands/MSBuildCommand.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class MSBuildCommand : SubCommandBase - { - public MSBuildCommand(CommandContext context) : base(context) - { - } - - private bool EnableBinaryLog => Environment.GetEnvironmentVariable("KOREBUILD_ENABLE_BINARY_LOG") == "1"; - - private List Arguments { get; set; } - - public override void Configure(CommandLineApplication application) - { - base.Configure(application); - Arguments = application.RemainingArguments; - } - - protected override int Execute() - { - Reporter.Verbose($"Building {Context.RepoPath}."); - Reporter.Verbose($"dotnet = {Context.RepoPath}"); - - if (Context.SDKVersion != "latest") - { - var globalFile = Path.Combine(Context.RepoPath, "global.json"); - File.WriteAllText(globalFile, $"{{ \"sdk\": {{ \"version\": \"{Context.SDKVersion}\" }} }}", System.Text.Encoding.ASCII); - } - else - { - Reporter.Verbose($"Skipping global.json generation because the SDKVersion = {Context.SDKVersion}"); - } - - var makeFileProj = Path.Combine(Context.KoreBuildDir, "KoreBuild.proj"); - var msBuildArtifactsDir = Path.Combine(Context.RepoPath, "artifacts", "msbuild"); - var msBuildResponseFile = Path.Combine(msBuildArtifactsDir, "msbuild.rsp"); - - var msBuildLogArgument = string.Empty; - - - if (EnableBinaryLog) - { - Reporter.Verbose("Enabling binary logging"); - var msBuildLogFilePath = Path.Combine(msBuildArtifactsDir, "msbuild.binlog"); - msBuildLogArgument = $"/bl:{msBuildLogFilePath}"; - } - - var msBuildArguments = string.Empty; - - foreach (var arg in Arguments) - { - msBuildArguments += Environment.NewLine + arg; - } - - // TODO: naturalize newlines - msBuildArguments += $@" -/nologo -/m -/p:RepositoryRoot={Context.RepoPath}\ -{msBuildLogArgument} -/clp:Summary -""{makeFileProj}"" -"; - - Directory.CreateDirectory(msBuildArtifactsDir); - - var noop = msBuildArguments.IndexOf("/t:Noop", StringComparison.OrdinalIgnoreCase) >= 0 - || msBuildArguments.IndexOf("/t:Cow", StringComparison.OrdinalIgnoreCase) >= 0; - - File.WriteAllText(msBuildResponseFile, msBuildArguments, System.Text.Encoding.ASCII); - Reporter.Verbose($"Noop = {noop}"); - var firstTime = Environment.GetEnvironmentVariable("DOTNET_SKIP_FIRST_TIME_EXPERIENCE"); - if (noop) - { - Environment.SetEnvironmentVariable("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true"); - } - else - { - var buildTaskResult = BuildTaskProject(Context.RepoPath); - if (buildTaskResult != 0) - { - return buildTaskResult; - } - } - - return RunDotnet(new[] { "msbuild", $@"@""{msBuildResponseFile}""" }); - } - - private int BuildTaskProject(string path) - { - var taskFolder = Path.Combine(Context.RepoPath, "build", "tasks"); - var taskProj = Path.Combine(taskFolder, "RepoTasks.csproj"); - var publishFolder = Path.Combine(taskFolder, "bin", "publish"); - - if (File.Exists(taskProj)) - { - if (File.Exists(publishFolder)) - { - Directory.Delete(publishFolder, recursive: true); - } - - var sdkPath = $"/p:RepoTasksSdkPath={Path.Combine(Context.KoreBuildDir, "msbuild", "KoreBuild.RepoTasks.Sdk", "Sdk")}"; - - var restoreResult = RunDotnet(new[] { "restore", taskProj, sdkPath }); - if (restoreResult != 0) - { - return restoreResult; - } - - return RunDotnet(new[] { "publish", taskProj, "--configuration", "Release", "--output", publishFolder, "/nologo", sdkPath }); - } - - return 0; - } - } -} diff --git a/tools/KoreBuild.Console/Commands/RootCommand.cs b/tools/KoreBuild.Console/Commands/RootCommand.cs deleted file mode 100644 index 6477f7e23..000000000 --- a/tools/KoreBuild.Console/Commands/RootCommand.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Reflection; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console.Commands -{ - internal class RootCommand : CommandBase - { - public override void Configure(CommandLineApplication application) - { - var context = new CommandContext(application); - - application.FullName = "korebuild"; - - application.Command("install-tools", new InstallToolsCommand(context).Configure, throwOnUnexpectedArg: false); - application.Command("install", c => { - c.HelpOption("-h|--help"); - c.Command("vs", new InstallToolsetsCommand(context).Configure, throwOnUnexpectedArg: false); - c.OnExecute(() => - { - c.ShowHelp(); - return 2; - }); - }); - application.Command("msbuild", new MSBuildCommand(context).Configure, throwOnUnexpectedArg: false); - application.Command("docker-build", new DockerBuildCommand(context).Configure, throwOnUnexpectedArg: false); - - // Commands that upgrade things - application.Command("upgrade", c => - { - c.HelpOption("-h|--help"); - c.Command("deps", new DependenciesUpgradeCommand(context).Configure, throwOnUnexpectedArg: false); - - c.OnExecute(() => - { - c.ShowHelp(); - return 2; - }); - }); - - // Commands that generate code and files - application.Command("generate", c => - { - c.HelpOption("-h|--help"); - - c.Command("deps", new DependenciesGenerateCommand(context).Configure, throwOnUnexpectedArg: false); - c.Command("api-baselines", new ApiBaselinesGenerateCommand(context).Configure, throwOnUnexpectedArg: false); - - c.OnExecute(() => - { - c.ShowHelp(); - return 2; - }); - }); - - application.VersionOption("--version", GetVersion); - - base.Configure(application); - } - - private static string GetVersion() - => typeof(RootCommand).GetTypeInfo().Assembly.GetCustomAttribute().InformationalVersion; - } -} diff --git a/tools/KoreBuild.Console/Commands/SubCommandBase.cs b/tools/KoreBuild.Console/Commands/SubCommandBase.cs deleted file mode 100644 index ecd7f088b..000000000 --- a/tools/KoreBuild.Console/Commands/SubCommandBase.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using Microsoft.Extensions.CommandLineUtils; -using Microsoft.Extensions.Tools.Internal; - -namespace KoreBuild.Console.Commands -{ - internal abstract class SubCommandBase : CommandBase - { - protected SubCommandBase(CommandContext context) - { - Context = context; - } - - protected CommandContext Context { get; } - - protected IReporter Reporter => Context.Reporter; - - protected override bool IsValid() - { - if (!Directory.Exists(Context.RepoPath)) - { - Context.Reporter.Error($"The RepoPath '{Context.RepoPath}' doesn't exist."); - return false; - } - - return base.IsValid(); - } - - protected int RunDotnet(params string[] arguments) - => RunDotnet(arguments, Directory.GetCurrentDirectory()); - - protected int RunDotnet(IEnumerable arguments, string workingDir) - { - var args = ArgumentEscaper.EscapeAndConcatenate(arguments); - - // use the dotnet.exe file used to start this process - var dotnet = DotNetMuxer.MuxerPath; - // if it could not be found, fallback to detecting DOTNET_HOME or PATH - dotnet = string.IsNullOrEmpty(dotnet) || !Path.IsPathRooted(dotnet) - ? Context.GetDotNetExecutable() - : dotnet; - - var psi = new ProcessStartInfo - { - FileName = dotnet, - Arguments = args, - WorkingDirectory = workingDir, - }; - - Reporter.Verbose($"Executing '{psi.FileName} {psi.Arguments}'"); - - var process = Process.Start(psi); - process.WaitForExit(); - - return process.ExitCode; - } - } -} diff --git a/tools/KoreBuild.Console/KoreBuild.Console.csproj b/tools/KoreBuild.Console/KoreBuild.Console.csproj deleted file mode 100644 index 83f28c5d4..000000000 --- a/tools/KoreBuild.Console/KoreBuild.Console.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - - Exe - netcoreapp3.0 - - - - - - - - - - - - diff --git a/tools/KoreBuild.Console/Program.cs b/tools/KoreBuild.Console/Program.cs deleted file mode 100644 index d12e72388..000000000 --- a/tools/KoreBuild.Console/Program.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using KoreBuild.Console.Commands; -using Microsoft.Extensions.CommandLineUtils; - -namespace KoreBuild.Console -{ - class Program - { - static int Main(string[] args) - { - var application = new CommandLineApplication() - { - Name = "korebuild" - }; - - new RootCommand().Configure(application); - - try - { - return application.Execute(args); - } - catch (Exception ex) - { - System.Console.Error.WriteLine($"Exception thrown: '{ex.ToString()}'"); - return 1; - } - } - } -} diff --git a/tools/KoreBuild.Console/Reporter/ConsoleReporter.cs b/tools/KoreBuild.Console/Reporter/ConsoleReporter.cs deleted file mode 100644 index a9fe89812..000000000 --- a/tools/KoreBuild.Console/Reporter/ConsoleReporter.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.Extensions.Tools.Internal -{ - public class ConsoleReporter : IReporter - { - private object _writeLock = new object(); - - public ConsoleReporter(IConsole console) - : this(console, verbose: false, quiet: false) - { } - - public ConsoleReporter(IConsole console, bool verbose, bool quiet) - { - Console = console; - IsVerbose = verbose; - IsQuiet = quiet; - } - - protected IConsole Console { get; } - public bool IsVerbose { get; set; } - public bool IsQuiet { get; set; } - - protected virtual void WriteLine(TextWriter writer, string message, ConsoleColor? color) - { - lock (_writeLock) - { - if (color.HasValue) - { - Console.ForegroundColor = color.Value; - } - - writer.WriteLine(message); - - if (color.HasValue) - { - Console.ResetColor(); - } - } - } - - public virtual void Error(string message) - => WriteLine(Console.Error, message, ConsoleColor.Red); - public virtual void Warn(string message) - => WriteLine(Console.Out, message, ConsoleColor.Yellow); - - public virtual void Output(string message) - { - if (IsQuiet) - { - return; - } - WriteLine(Console.Out, message, color: null); - } - - public virtual void Verbose(string message) - { - if (!IsVerbose) - { - return; - } - - WriteLine(Console.Out, message, ConsoleColor.DarkGray); - } - } -} diff --git a/tools/KoreBuild.Console/Reporter/IConsole.cs b/tools/KoreBuild.Console/Reporter/IConsole.cs deleted file mode 100644 index 46cae4a05..000000000 --- a/tools/KoreBuild.Console/Reporter/IConsole.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.Extensions.Tools.Internal -{ - public interface IConsole - { - event ConsoleCancelEventHandler CancelKeyPress; - TextWriter Out { get; } - TextWriter Error { get; } - TextReader In { get; } - bool IsInputRedirected { get; } - bool IsOutputRedirected { get; } - bool IsErrorRedirected { get; } - ConsoleColor ForegroundColor { get; set; } - void ResetColor(); - } -} diff --git a/tools/KoreBuild.Console/Reporter/IReporter.cs b/tools/KoreBuild.Console/Reporter/IReporter.cs deleted file mode 100644 index e57261401..000000000 --- a/tools/KoreBuild.Console/Reporter/IReporter.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.Tools.Internal -{ - public interface IReporter - { - void Verbose(string message); - void Output(string message); - void Warn(string message); - void Error(string message); - bool IsVerbose { get; } - } -} diff --git a/tools/KoreBuild.Console/Reporter/PhysicalConsole.cs b/tools/KoreBuild.Console/Reporter/PhysicalConsole.cs deleted file mode 100644 index 429342ecc..000000000 --- a/tools/KoreBuild.Console/Reporter/PhysicalConsole.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.Extensions.Tools.Internal -{ - public class PhysicalConsole : IConsole - { - private PhysicalConsole() - { - Console.CancelKeyPress += (o, e) => - { - CancelKeyPress?.Invoke(o, e); - }; - } - - public static IConsole Singleton { get; } = new PhysicalConsole(); - - public event ConsoleCancelEventHandler CancelKeyPress; - public TextWriter Error => Console.Error; - public TextReader In => Console.In; - public TextWriter Out => Console.Out; - public bool IsInputRedirected => Console.IsInputRedirected; - public bool IsOutputRedirected => Console.IsOutputRedirected; - public bool IsErrorRedirected => Console.IsErrorRedirected; - public ConsoleColor ForegroundColor - { - get => Console.ForegroundColor; - set => Console.ForegroundColor = value; - } - - public void ResetColor() => Console.ResetColor(); - } -} diff --git a/version.props b/version.props index 0601f1fd6..92574ffa4 100644 --- a/version.props +++ b/version.props @@ -1,8 +1,8 @@ - master + feature/vs2019 3.0.0 - build + build-feat-vs2019 t000 $(VersionSuffix)-$(BuildNumber) From cc6886de9fb992c54e0c859d6347344bd4658423 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 6 Feb 2019 07:50:00 -0800 Subject: [PATCH 2/5] Build the feature/vs2019 branch on CI --- .azure/pipelines/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.azure/pipelines/ci.yml b/.azure/pipelines/ci.yml index 8ac3ac6f5..376a173d7 100644 --- a/.azure/pipelines/ci.yml +++ b/.azure/pipelines/ci.yml @@ -4,6 +4,7 @@ trigger: include: - master - release/* + - feature/vs2019 # Trigger builds for PRs to any branch pr: From d674d98e72c654d4802f20a0fb11ee0f8fdb5426 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Wed, 13 Feb 2019 17:36:50 -0800 Subject: [PATCH 3/5] Revert references to feature/vs2019 channel to 'master' --- .azure/pipelines/ci.yml | 1 - korebuild.json | 2 +- testassets/RepoThatShouldFailToBuild/korebuild.json | 2 +- testassets/RepoWithGlobalTool/korebuild.json | 2 +- testassets/SimpleRepo/korebuild.json | 2 +- version.props | 4 ++-- 6 files changed, 6 insertions(+), 7 deletions(-) diff --git a/.azure/pipelines/ci.yml b/.azure/pipelines/ci.yml index 376a173d7..8ac3ac6f5 100644 --- a/.azure/pipelines/ci.yml +++ b/.azure/pipelines/ci.yml @@ -4,7 +4,6 @@ trigger: include: - master - release/* - - feature/vs2019 # Trigger builds for PRs to any branch pr: diff --git a/korebuild.json b/korebuild.json index 629b9c1d6..d25839fd1 100644 --- a/korebuild.json +++ b/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "./tools/korebuild.schema.json", - "channel": "feature/vs2019" + "channel": "master" } diff --git a/testassets/RepoThatShouldFailToBuild/korebuild.json b/testassets/RepoThatShouldFailToBuild/korebuild.json index 2d2c95708..8a276a7f3 100644 --- a/testassets/RepoThatShouldFailToBuild/korebuild.json +++ b/testassets/RepoThatShouldFailToBuild/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "feature/vs2019" + "channel": "master" } diff --git a/testassets/RepoWithGlobalTool/korebuild.json b/testassets/RepoWithGlobalTool/korebuild.json index 2d2c95708..8a276a7f3 100644 --- a/testassets/RepoWithGlobalTool/korebuild.json +++ b/testassets/RepoWithGlobalTool/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "feature/vs2019" + "channel": "master" } diff --git a/testassets/SimpleRepo/korebuild.json b/testassets/SimpleRepo/korebuild.json index 2d2c95708..8a276a7f3 100644 --- a/testassets/SimpleRepo/korebuild.json +++ b/testassets/SimpleRepo/korebuild.json @@ -1,4 +1,4 @@ { "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "feature/vs2019" + "channel": "master" } diff --git a/version.props b/version.props index 92574ffa4..0601f1fd6 100644 --- a/version.props +++ b/version.props @@ -1,8 +1,8 @@ - feature/vs2019 + master 3.0.0 - build-feat-vs2019 + build t000 $(VersionSuffix)-$(BuildNumber) From f87647ab7237d9ab16db6e210105679e68c0e035 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 14 Feb 2019 10:22:40 -0800 Subject: [PATCH 4/5] PR feedback --- build/repo.targets | 2 - files/KoreBuild/KoreBuild.sh | 2 +- .../build/DotNetTool.targets | 21 -------- .../build/Internal.AspNetCore.Sdk.targets | 4 -- .../SimpleRepoTests.cs | 53 ------------------- .../RepoWithGlobalTool/Directory.Build.props | 1 - .../Directory.Build.targets | 4 -- .../RepoWithGlobalTool/RepoWithGlobalTool.sln | 34 ------------ .../build/dependencies.props | 5 -- testassets/RepoWithGlobalTool/korebuild.json | 4 -- .../GlobalConsoleTool.csproj | 10 ---- .../src/GlobalConsoleTool/Program.cs | 12 ----- .../src/Simple.CliTool/Simple.CliTool.csproj | 1 - 13 files changed, 1 insertion(+), 152 deletions(-) delete mode 100644 src/Internal.AspNetCore.Sdk/build/DotNetTool.targets delete mode 100644 testassets/RepoWithGlobalTool/Directory.Build.props delete mode 100644 testassets/RepoWithGlobalTool/Directory.Build.targets delete mode 100644 testassets/RepoWithGlobalTool/RepoWithGlobalTool.sln delete mode 100644 testassets/RepoWithGlobalTool/build/dependencies.props delete mode 100644 testassets/RepoWithGlobalTool/korebuild.json delete mode 100644 testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj delete mode 100644 testassets/RepoWithGlobalTool/src/GlobalConsoleTool/Program.cs diff --git a/build/repo.targets b/build/repo.targets index 95ac7d81c..5f90e60fa 100644 --- a/build/repo.targets +++ b/build/repo.targets @@ -79,8 +79,6 @@ - - diff --git a/files/KoreBuild/KoreBuild.sh b/files/KoreBuild/KoreBuild.sh index 74eadaffb..952a8b4af 100755 --- a/files/KoreBuild/KoreBuild.sh +++ b/files/KoreBuild/KoreBuild.sh @@ -72,7 +72,7 @@ invoke_korebuild_command(){ elif [ "$command" = "install-tools" ]; then __install_tools "$tools_source" "$dot_net_home" else - __error "Unrecognized command $command" + __error "Unrecognized command '$command'" exit 1 fi } diff --git a/src/Internal.AspNetCore.Sdk/build/DotNetTool.targets b/src/Internal.AspNetCore.Sdk/build/DotNetTool.targets deleted file mode 100644 index d4bbb768c..000000000 --- a/src/Internal.AspNetCore.Sdk/build/DotNetTool.targets +++ /dev/null @@ -1,21 +0,0 @@ - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - $(GetSignedPackageFilesDependsOn);_GetSignedPackageFilesForGeneratedShims - $(OutDir) - - - - - <_ShimRids Include="$(PackAsToolShimRuntimeIdentifiers)" /> - - tools/$(TargetFramework)/any/shims/%(_ShimRids.Identity)/ - - - tools/$(TargetFramework)/any/$(TargetFileName) - - - - - diff --git a/src/Internal.AspNetCore.Sdk/build/Internal.AspNetCore.Sdk.targets b/src/Internal.AspNetCore.Sdk/build/Internal.AspNetCore.Sdk.targets index 5f76a7bfc..0551a59c3 100644 --- a/src/Internal.AspNetCore.Sdk/build/Internal.AspNetCore.Sdk.targets +++ b/src/Internal.AspNetCore.Sdk/build/Internal.AspNetCore.Sdk.targets @@ -7,10 +7,6 @@ for use outside of Microsoft. - - diff --git a/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs b/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs index dd810e789..4ddc095a1 100644 --- a/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs +++ b/test/KoreBuild.FunctionalTests/SimpleRepoTests.cs @@ -54,59 +54,6 @@ public void FullBuildCompletes() } } - [Fact(Skip = "Blocked on https://github.com/dotnet/sdk/issues/2867")] - public void BuildOfGlobalCliToolIncludesShims() - { - var app = _fixture.CreateTestApp("RepoWithGlobalTool"); - - var build = app.ExecuteBuild(_output, "/p:BuildNumber=0001"); - - Assert.Equal(0, build); - - var artifactsDir = Path.Combine(app.WorkingDirectory, "artifacts", "build"); - - var pkg = Path.Combine(artifactsDir, "GlobalConsoleTool.1.0.0.nupkg"); - using (var reader = new PackageArchiveReader(pkg)) - { - var files = reader.GetFiles(); - foreach (var file in files) - { - _output.WriteLine("pkg: " + file); - } - - var winx86 = Assert.Single(files, f => f.StartsWith("tools/netcoreapp3.0/any/shims/win-x86/")); - Assert.Equal("GlobalConsoleTool.exe", Path.GetFileName(winx86)); - - var winx64 = Assert.Single(files, f => f.StartsWith("tools/netcoreapp3.0/any/shims/win-x64/")); - Assert.Equal("GlobalConsoleTool.exe", Path.GetFileName(winx64)); - } - - var toolsDir = Path.Combine(app.WorkingDirectory, "artifacts", "tools"); - var installPsi = new ProcessStartInfo - { - FileName = DotNetMuxer.MuxerPathOrDefault(), - Arguments = ArgumentEscaper.EscapeAndConcatenate(new[] - { - "tool", - "install", - "--tool-path", toolsDir, - "GlobalConsoleTool", - "--add-source", artifactsDir - }), - }; - var install = app.Run(_output, installPsi); - Assert.Equal(0, install); - - var ext = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? ".exe" - : string.Empty; - var run = app.Run(_output, new ProcessStartInfo - { - FileName = Path.Combine(toolsDir, "GlobalConsoleTool" + ext), - }); - Assert.Equal(0, run); - } - [Fact] public void BuildShouldReturnNonZeroCode() { diff --git a/testassets/RepoWithGlobalTool/Directory.Build.props b/testassets/RepoWithGlobalTool/Directory.Build.props deleted file mode 100644 index 058246e40..000000000 --- a/testassets/RepoWithGlobalTool/Directory.Build.props +++ /dev/null @@ -1 +0,0 @@ - diff --git a/testassets/RepoWithGlobalTool/Directory.Build.targets b/testassets/RepoWithGlobalTool/Directory.Build.targets deleted file mode 100644 index b207ca315..000000000 --- a/testassets/RepoWithGlobalTool/Directory.Build.targets +++ /dev/null @@ -1,4 +0,0 @@ - - diff --git a/testassets/RepoWithGlobalTool/RepoWithGlobalTool.sln b/testassets/RepoWithGlobalTool/RepoWithGlobalTool.sln deleted file mode 100644 index af58340cc..000000000 --- a/testassets/RepoWithGlobalTool/RepoWithGlobalTool.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 -MinimumVisualStudioVersion = 15.0.26124.0 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GlobalConsoleTool", "src\GlobalConsoleTool\GlobalConsoleTool.csproj", "{4F0E73BA-1E8D-41B2-8FE8-59E58228224F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|x64.ActiveCfg = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|x64.Build.0 = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|x86.ActiveCfg = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Debug|x86.Build.0 = Debug|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|Any CPU.Build.0 = Release|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|x64.ActiveCfg = Release|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|x64.Build.0 = Release|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|x86.ActiveCfg = Release|Any CPU - {4F0E73BA-1E8D-41B2-8FE8-59E58228224F}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/testassets/RepoWithGlobalTool/build/dependencies.props b/testassets/RepoWithGlobalTool/build/dependencies.props deleted file mode 100644 index a932d8361..000000000 --- a/testassets/RepoWithGlobalTool/build/dependencies.props +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/testassets/RepoWithGlobalTool/korebuild.json b/testassets/RepoWithGlobalTool/korebuild.json deleted file mode 100644 index 8a276a7f3..000000000 --- a/testassets/RepoWithGlobalTool/korebuild.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/aspnet/BuildTools/master/tools/korebuild.schema.json", - "channel": "master" -} diff --git a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj b/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj deleted file mode 100644 index bd90560e4..000000000 --- a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/GlobalConsoleTool.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - netcoreapp3.0 - true - win-x64;win-x86 - - - diff --git a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/Program.cs b/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/Program.cs deleted file mode 100644 index e91098a2b..000000000 --- a/testassets/RepoWithGlobalTool/src/GlobalConsoleTool/Program.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace GlobalConsoleTool -{ - class Program - { - static void Main(string[] args) - { - Console.WriteLine("Hello World!"); - } - } -} diff --git a/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj b/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj index 4a9b18dab..2ea5a7ef8 100644 --- a/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj +++ b/testassets/SimpleRepo/src/Simple.CliTool/Simple.CliTool.csproj @@ -7,7 +7,6 @@ cowsay Simple.CliTool true - TestCert MyPackageSigningCert From 52199d5cc30634e6a7753847ecdfda8e1bcf3c87 Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 14 Feb 2019 12:32:32 -0800 Subject: [PATCH 5/5] Allow overriding properties affecting layout of artifacts dir --- files/KoreBuild/KoreBuild.Common.props | 4 ++-- modules/KoreBuild.Tasks/CodeSign.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/files/KoreBuild/KoreBuild.Common.props b/files/KoreBuild/KoreBuild.Common.props index ca89a5055..c2fa69dab 100644 --- a/files/KoreBuild/KoreBuild.Common.props +++ b/files/KoreBuild/KoreBuild.Common.props @@ -37,8 +37,8 @@ Default layout and configuration. $([MSBuild]::NormalizeDirectory('$(RepositoryRoot)')) $([MSBuild]::NormalizeDirectory('$(RepositoryRoot)'))artifacts\ $(ArtifactsDir)build\ - $(ArtifactsDir)logs\ - $([MSBuild]::NormalizeDirectory('$(RepositoryRoot)'))obj\ + $(ArtifactsDir)logs\ + $([MSBuild]::NormalizeDirectory('$(RepositoryRoot)'))obj\ $(NUGET_PACKAGES) $(USERPROFILE)\.nuget\packages\ diff --git a/modules/KoreBuild.Tasks/CodeSign.props b/modules/KoreBuild.Tasks/CodeSign.props index 9ed3e61b3..fed0d924f 100644 --- a/modules/KoreBuild.Tasks/CodeSign.props +++ b/modules/KoreBuild.Tasks/CodeSign.props @@ -21,7 +21,7 @@ true - +