We no longer require Cake build nor we use it extensively!
Update Azure Pipelines (CI YAML) Script to be more modern and runnable across platforms.
Replaced the headers check with a PowerShell script mimicking the Cake script's `UpdateHeaders` task functionality.
This commit is contained in:
Nirmal Guru 2022-01-25 17:53:53 +05:30 коммит произвёл GitHub
Родитель c5ab771da4
Коммит ea1010575d
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
8 изменённых файлов: 107 добавлений и 446 удалений

Просмотреть файл

@ -18,9 +18,9 @@ jobs:
# Install NuGet
- task: NuGetToolInstaller@0
displayName: Install NuGet 5.6.0
displayName: Install NuGet 6.0
inputs:
versionSpec: 5.6.0
versionSpec: 6.0.0
# Install NerdBank GitVersioning
- task: DotNetCoreCLI@2
@ -28,28 +28,30 @@ jobs:
inputs:
command: custom
custom: tool
arguments: install --tool-path . nbgv
arguments: install -g nbgv
# Set Build Version
- script: nbgv cloud
displayName: Set NBGV version
# Verify headers
- powershell: .\build\build.ps1 -Target Verify
- pwsh: build/Update-Headers.ps1 -Verify
displayName: Verify headers
# Build solution
- powershell: dotnet build -c Release
- script: dotnet build -c Release
displayName: Build solution
# Run .NET 6 tests
- powershell: dotnet test --logger "trx;LogFileName=VsTestResultsNet6.trx" --framework net6.0 --configuration Release
- script: dotnet test -c Release -f net6.0 -l "trx;LogFileName=VSTestResults_net6.0.trx"
displayName: Run .NET 6 unit tests
# Run .NET Core 3.1 tests
- powershell: dotnet test --logger "trx;LogFileName=VsTestResultsNetCore31.trx" --framework netcoreapp3.1 --configuration Release
- script: dotnet test -c Release -f netcoreapp3.1 -l "trx;LogFileName=VSTestResults_netcoreapp3.1.trx"
displayName: Run .NET Core 3.1 unit tests
# Run .NET Framework 4.7.2 tests
- powershell: dotnet test --logger "trx;LogFileName=VsTestResultsNet472.trx" --framework net472 --configuration Release
- script: dotnet test -c Release -f net472 -l "trx;LogFileName=VSTestResults_net472.trx"
displayName: Run .NET Framework 4.7.2 unit tests
# Publish test results
@ -57,27 +59,23 @@ jobs:
displayName: Publish test results
inputs:
testResultsFormat: 'VSTest'
testResultsFiles: '**/VsTestResults*.trx'
testResultsFiles: '**/VSTestResults*.trx'
condition: always()
# Create the NuGet package(s)
- powershell: dotnet pack --configuration Release
- script: dotnet pack -c Release
displayName: Create NuGet package(s)
# Sign package(s)
- task: PowerShell@2
- pwsh: build/Sign-Package.ps1
displayName: Authenticode sign packages
inputs:
filePath: build/Sign-Package.ps1
env:
SignClientUser: $(SignClientUser)
SignClientSecret: $(SignClientSecret)
ArtifactDirectory: bin\nupkg
condition: and(succeeded(), not(eq(variables['build.reason'], 'PullRequest')), not(eq(variables['SignClientSecret'], '')), not(eq(variables['SignClientUser'], '')))
ArtifactDirectory: bin/nupkg
condition: and(succeeded(), not(eq(variables['Build.Reason'], 'PullRequest')), not(eq(variables['SignClientSecret'], '')), not(eq(variables['SignClientUser'], '')))
# Publish build artifacts
- task: PublishPipelineArtifact@1
- publish: bin/nupkg
artifact: Packages
displayName: Publish package artifacts
inputs:
targetPath: .\bin\nupkg
artifactName: Packages

Просмотреть файл

@ -1,3 +0,0 @@
@ECHO OFF
PowerShell.exe -file "%~dp0build.ps1"
PAUSE

89
build/Update-Headers.ps1 Normal file
Просмотреть файл

@ -0,0 +1,89 @@
# Script to Update Header comment in C# sources within this repository.
# This script duplicates the fuctionality provided by the 'UpdateHeaders' target in Cake script present previously.
# Since, Cake build has been removed, this fuctionality has been implimented here in this PowerShell script.
[CmdletBinding()]
Param(
[Alias("Verify")]
[switch]$DryRun,
[switch]$Clean
)
function Clear-BuildArtifacts {
if (Get-Command dotnet) {
Write-Host "Starting 'dotnet msbuild -t:Clean' to clean-up build outputs"
dotnet msbuild -noLogo -noAutoRsp -v:m -t:Clean
}
elseif (Get-Command msbuild) {
Write-Host "Starting 'msbuild -t:Clean' to clean-up build outputs"
msbuild -noLogo -noAutoRsp -v:m -t:Clean
}
elseif (Get-Command git) {
Write-Host "Starting 'git clean -Xdf' to clean-up build outputs"
git clean -Xdf
}
else {
Write-Warning "Can't find dotnet/msbuild/git to clean-up build outputs"
}
}
function Get-SourceFiles ([string]$Path, [string]$Extension) {
$fileType = $Extension.TrimStart('.')
$fileFilter = "*.$fileType"
$fileExcludes = "*.g.$fileType", "*.i.$fileType", "*TemporaryGeneratedFile*.$fileType"
$sourceFiles = Get-ChildItem -Path $Path -File -Recurse -Filter $fileFilter -Exclude $fileExcludes
return $sourceFiles.Where({ !($_.FullName.Contains("\bin\") -or $_.FullName.Contains("\obj\")) })
}
# Set Repot Root
$repoRoot = Split-Path -Path $PSScriptRoot -Parent
Push-Location $repoRoot
# Clean-up Repository build outputs
if ($Clean) {
Clear-BuildArtifacts
}
# Get C# source files recursively
$sourceFiles = Get-SourceFiles -Path $repoRoot -Extension ".cs"
Write-Host "Checking $($sourceFiles.Count) C# file header(s)"
$hasMissing = $false
foreach ($sourceFile in $sourceFiles) {
$oldContent = Get-Content $sourceFile -Raw | Out-String -NoNewline
if ($oldContent.Contains("// <auto-generated/>") -or $oldContent.Contains("// <auto-generated>")) {
continue
}
$headerFilePath = Join-Path $PSScriptRoot "header.txt"
$headerContent = Get-Content $headerFilePath -Raw | Out-String
$regexHeader = "^(//.*\r?\n)*\r?\n"
$newContent = $oldContent -replace $regexHeader,$headerContent | Out-String -NoNewline
if (-not ($newContent -eq $oldContent)) {
$sourceFilePath = [System.IO.Path]::GetRelativePath($repoRoot, $sourceFile.FullName)
if ($DryRun) {
Write-Warning "Wrong/missing file header in '$sourceFilePath'"
$hasMissing = $true
}
else {
Write-Host "Updating '$sourceFilePath' file header..."
Set-Content -Path $sourceFile -Value $newContent -NoNewline
}
}
}
if ($DryRun -and $hasMissing) {
Write-Error "Please run 'Update-Headers.ps1' to verify and add missing headers ins source files before commiting your changes."
}
else {
Write-Host "All $($sourceFiles.Count) C# file header(s) are up to date."
}
# Pop out of Repo Root
Pop-Location

Просмотреть файл

@ -1,3 +0,0 @@
@ECHO OFF
PowerShell.exe -file "%~dp0build.ps1" -Target UpdateHeaders
PAUSE

Просмотреть файл

@ -1,120 +0,0 @@
#module nuget:?package=Cake.LongPath.Module&version=1.0.1
#addin nuget:?package=Cake.FileHelpers&version=4.0.1
#addin nuget:?package=Cake.Powershell&version=1.0.1
#addin nuget:?package=Cake.GitVersioning&version=3.4.220
#tool nuget:?package=MSTest.TestAdapter&version=2.2.5
#tool nuget:?package=vswhere&version=2.8.4
using System;
using System.Linq;
using System.Text.RegularExpressions;
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
//////////////////////////////////////////////////////////////////////
// VARIABLES
//////////////////////////////////////////////////////////////////////
var baseDir = MakeAbsolute(Directory("../")).ToString();
var binDir = baseDir + "/bin";
//////////////////////////////////////////////////////////////////////
// METHODS
//////////////////////////////////////////////////////////////////////
void VerifyHeaders(bool Replace)
{
var header = FileReadText("header.txt") + "\r\n";
bool hasMissing = false;
Func<IFileSystemInfo, bool> exclude_objDir = fileSystemInfo => !fileSystemInfo.Path.Segments.Contains("obj");
var files = GetFiles(baseDir + "/**/*.cs", new GlobberSettings { Predicate = exclude_objDir }).Where(file =>
{
var path = file.ToString();
return !(path.EndsWith(".g.cs") || path.EndsWith(".i.cs") || System.IO.Path.GetFileName(path).Contains("TemporaryGeneratedFile"));
});
Information("\nChecking " + files.Count() + " file header(s)");
foreach(var file in files)
{
var oldContent = FileReadText(file);
if(oldContent.Contains("// <auto-generated>") ||
oldContent.Contains("// <auto-generated/>"))
{
continue;
}
var rgx = new Regex("^(//.*\r?\n)*\r?\n");
var newContent = header + rgx.Replace(oldContent, "");
if(!newContent.Equals(oldContent, StringComparison.Ordinal))
{
if(Replace)
{
Information("\nUpdating " + file + " header...");
FileWriteText(file, newContent);
}
else
{
Error("\nWrong/missing header on " + file);
hasMissing = true;
}
}
}
if(!Replace && hasMissing)
{
throw new Exception("Please run UpdateHeaders.bat or '.\\build.ps1 -Target UpdateHeaders' and commit the changes.");
}
}
//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////
Task("Clean")
.Description("Cleans the output folder")
.Does(() =>
{
if(DirectoryExists(binDir))
{
Information("\nCleaning working directory");
CleanDirectory(binDir);
}
else
{
CreateDirectory(binDir);
}
});
Task("Verify")
.Description("Verifies the headers in *.cs files")
.IsDependentOn("Clean")
.Does(() =>
{
VerifyHeaders(false);
});
Task("UpdateHeaders")
.Description("Updates the headers in *.cs files")
.Does(() =>
{
VerifyHeaders(true);
});
//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////
RunTarget(target);

Просмотреть файл

@ -1,287 +0,0 @@
##########################################################################
# This is the Cake bootstrapper script for PowerShell.
# This file was downloaded from https://github.com/cake-build/resources
# Feel free to change this file to fit your needs.
##########################################################################
<#
.SYNOPSIS
This is a Powershell script to bootstrap a Cake build.
.DESCRIPTION
This Powershell script will download NuGet if missing, restore NuGet tools (including Cake)
and execute your Cake build script with the parameters you provide.
.PARAMETER Script
The build script to execute.
.PARAMETER Target
The build script target to run.
.PARAMETER Configuration
The build configuration to use.
.PARAMETER Verbosity
Specifies the amount of information to be displayed.
.PARAMETER ShowDescription
Shows description about tasks.
.PARAMETER DryRun
Performs a dry run.
.PARAMETER SkipToolPackageRestore
Skips restoring of packages.
.PARAMETER ScriptArgs
Remaining arguments are added here.
.LINK
https://cakebuild.net
#>
[CmdletBinding()]
Param(
[string]$Script,
[string]$Target,
[string]$Configuration,
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity,
[switch]$ShowDescription,
[Alias("WhatIf", "Noop")]
[switch]$DryRun,
[switch]$SkipToolPackageRestore,
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$ScriptArgs
)
# This is an automatic variable in PowerShell Core, but not in Windows PowerShell 5.x
if (-not (Test-Path variable:global:IsCoreCLR)) {
$IsCoreCLR = $false
}
# Attempt to set highest encryption available for SecurityProtocol.
# PowerShell will not set this by default (until maybe .NET 4.6.x). This
# will typically produce a message for PowerShell v2 (just an info
# message though)
try {
# Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48)
# Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't
# exist in .NET 4.0, even though they are addressable if .NET 4.5+ is
# installed (.NET 4.5 is an in-place upgrade).
# PowerShell Core already has support for TLS 1.2 so we can skip this if running in that.
if (-not $IsCoreCLR) {
[System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48
}
} catch {
Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3'
}
[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
function MD5HashFile([string] $filePath)
{
if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf))
{
return $null
}
[System.IO.Stream] $file = $null;
[System.Security.Cryptography.MD5] $md5 = $null;
try
{
$md5 = [System.Security.Cryptography.MD5]::Create()
$file = [System.IO.File]::OpenRead($filePath)
return [System.BitConverter]::ToString($md5.ComputeHash($file))
}
finally
{
if ($null -ne $file)
{
$file.Dispose()
}
if ($null -ne $md5)
{
$md5.Dispose()
}
}
}
function GetProxyEnabledWebClient
{
$wc = New-Object System.Net.WebClient
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$wc.Proxy = $proxy
return $wc
}
Write-Host "Preparing to run build script..."
if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}
if(!$Script){
$Script = Join-Path $PSScriptRoot "build.cake"
}
$TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$ADDINS_DIR = Join-Path $TOOLS_DIR "Addins"
$MODULES_DIR = Join-Path $TOOLS_DIR "Modules"
$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe"
$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe"
$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config"
$PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum"
$ADDINS_PACKAGES_CONFIG = Join-Path $ADDINS_DIR "packages.config"
$MODULES_PACKAGES_CONFIG = Join-Path $MODULES_DIR "packages.config"
$env:CAKE_PATHS_TOOLS = $TOOLS_DIR
$env:CAKE_PATHS_ADDINS = $ADDINS_DIR
$env:CAKE_PATHS_MODULES = $MODULES_DIR
# Make sure tools folder exists
if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) {
Write-Verbose -Message "Creating tools directory..."
New-Item -Path $TOOLS_DIR -Type Directory | Out-Null
}
# Make sure that packages.config exist.
if (!(Test-Path $PACKAGES_CONFIG)) {
Write-Verbose -Message "Downloading packages.config..."
try {
$wc = GetProxyEnabledWebClient
$wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG)
} catch {
Throw "Could not download packages.config."
}
}
# Try find NuGet.exe in path if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Trying to find nuget.exe in PATH..."
$existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_ -PathType Container) }
$NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1
if ($null -ne $NUGET_EXE_IN_PATH -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) {
Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)."
$NUGET_EXE = $NUGET_EXE_IN_PATH.FullName
}
}
# Try download NuGet.exe if not exists
if (!(Test-Path $NUGET_EXE)) {
Write-Verbose -Message "Downloading NuGet.exe..."
try {
$wc = GetProxyEnabledWebClient
$wc.DownloadFile($NUGET_URL, $NUGET_EXE)
} catch {
Throw "Could not download NuGet.exe."
}
}
# These are automatic variables in PowerShell Core, but not in Windows PowerShell 5.x
if (-not (Test-Path variable:global:IsMacOS)) {
$IsLinux = $false
$IsMacOS = $false
}
# Save nuget.exe path to environment to be available to child processed
$env:NUGET_EXE = $NUGET_EXE
$env:NUGET_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) {
"mono `"$NUGET_EXE`""
} else {
"`"$NUGET_EXE`""
}
# Restore tools from NuGet?
if(-Not $SkipToolPackageRestore.IsPresent) {
Push-Location
Set-Location $TOOLS_DIR
# Check for changes in packages.config and remove installed tools if true.
[string] $md5Hash = MD5HashFile $PACKAGES_CONFIG
if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or
($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) {
Write-Verbose -Message "Missing or changed package.config hash..."
Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery |
Remove-Item -Recurse -Force
}
Write-Verbose -Message "Restoring tools from NuGet..."
$NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet tools."
}
else
{
$md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII"
}
Write-Verbose -Message ($NuGetOutput | Out-String)
Pop-Location
}
# Restore addins from NuGet
if (Test-Path $ADDINS_PACKAGES_CONFIG) {
Push-Location
Set-Location $ADDINS_DIR
Write-Verbose -Message "Restoring addins from NuGet..."
$NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$ADDINS_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet addins."
}
Write-Verbose -Message ($NuGetOutput | Out-String)
Pop-Location
}
# Restore modules from NuGet
if (Test-Path $MODULES_PACKAGES_CONFIG) {
Push-Location
Set-Location $MODULES_DIR
Write-Verbose -Message "Restoring modules from NuGet..."
$NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$MODULES_DIR`""
if ($LASTEXITCODE -ne 0) {
Throw "An error occurred while restoring NuGet modules."
}
Write-Verbose -Message ($NuGetOutput | Out-String)
Pop-Location
}
# Make sure that Cake has been installed.
if (!(Test-Path $CAKE_EXE)) {
Throw "Could not find Cake.exe at $CAKE_EXE"
}
$CAKE_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) {
"mono `"$CAKE_EXE`""
} else {
"`"$CAKE_EXE`""
}
# Build an array (not a string) of Cake arguments to be joined later
$cakeArguments = @()
if ($Script) { $cakeArguments += "`"$Script`"" }
if ($Target) { $cakeArguments += "--target=`"$Target`"" }
if ($Configuration) { $cakeArguments += "--configuration=$Configuration" }
if ($Verbosity) { $cakeArguments += "--verbosity=$Verbosity" }
if ($ShowDescription) { $cakeArguments += "--showdescription" }
if ($DryRun) { $cakeArguments += "--dryrun" }
$cakeArguments += $ScriptArgs
# Start Cake
Write-Host "Running build script..."
Invoke-Expression "& $CAKE_EXE_INVOCATION $($cakeArguments -join " ")"
$cakeExitCode = $LASTEXITCODE
# Clean up environment variables that were created earlier in this bootstrapper
$env:CAKE_PATHS_TOOLS = $null
$env:CAKE_PATHS_ADDINS = $null
$env:CAKE_PATHS_MODULES = $null
# Return exit code
exit $cakeExitCode

Просмотреть файл

@ -1,3 +0,0 @@
<packages>
<package id="Cake" version="1.1.0" />
</packages>

Просмотреть файл

@ -50,22 +50,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommunityToolkit.Common.Uni
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{CD16E790-7B7B-411E-9CE7-768E759CC22D}"
ProjectSection(SolutionItems) = preProject
build\Build.bat = build\Build.bat
build\build.cake = build\build.cake
build\build.ps1 = build\build.ps1
build\Community.Toolkit.Common.props = build\Community.Toolkit.Common.props
build\Community.Toolkit.Common.targets = build\Community.Toolkit.Common.targets
build\header.txt = build\header.txt
build\nuget.png = build\nuget.png
build\Sign-Package.ps1 = build\Sign-Package.ps1
build\SignClientSettings.json = build\SignClientSettings.json
build\StyleXaml.bat = build\StyleXaml.bat
build\UpdateHeaders.bat = build\UpdateHeaders.bat
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{11CB82CB-F72A-4690-9C0F-0AD5303C79B6}"
ProjectSection(SolutionItems) = preProject
build\tools\packages.config = build\tools\packages.config
build\Update-Headers.ps1 = build\Update-Headers.ps1
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Configuration", "Configuration", "{6640D447-C28D-4DBB-91F4-3ADCE0CA64AD}"
@ -383,7 +374,6 @@ Global
{59212E0A-878C-4097-A1CE-58CE3375F8D7} = {B30036C4-D514-4E5B-A323-587A061772CE}
{17522D0B-CA70-40B6-AFD8-8B8D45E75D92} = {B30036C4-D514-4E5B-A323-587A061772CE}
{CD16E790-7B7B-411E-9CE7-768E759CC22D} = {CFA75BE0-5A44-45DE-8114-426A605B062B}
{11CB82CB-F72A-4690-9C0F-0AD5303C79B6} = {CD16E790-7B7B-411E-9CE7-768E759CC22D}
{6640D447-C28D-4DBB-91F4-3ADCE0CA64AD} = {B30036C4-D514-4E5B-A323-587A061772CE}
{9E09DA49-4389-4ECE-8B68-EBDB1221DA90} = {6640D447-C28D-4DBB-91F4-3ADCE0CA64AD}
{743D74BA-12AE-4639-AD77-B9DDA9C03255} = {B30036C4-D514-4E5B-A323-587A061772CE}