From 66c49b1e09ceff072a9725594644c354dc6b3e7d Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Mon, 24 Oct 2022 18:49:54 -0500 Subject: [PATCH 01/10] Swap cake for direct msbuild invocation --- azure-pipelines.yml | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1f99bc1..482dcbe 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -48,14 +48,18 @@ steps: - powershell: .\build\Install-WindowsSdkISO.ps1 18362 - task: DotNetCoreCLI@2 + displayName: NuGet restore inputs: command: custom custom: msbuild - arguments: /t:restore .\ColorCode.sln - displayName: NuGet restore + arguments: -p:Configuration=Release -t:restore .\ColorCode.sln -- powershell: .\build\build.ps1 - displayName: Build +- task: DotNetCoreCLI@2 + displayName: Build and pack + inputs: + command: custom + custom: msbuild + arguments: -p:Configuration=Release -t:pack .\ColorCode.sln - task: PowerShell@2 displayName: Authenticode Sign Packages @@ -70,6 +74,6 @@ steps: - task: PublishBuildArtifacts@1 displayName: Publish Package Artifacts inputs: - pathToPublish: .\build\nupkg + pathToPublish: .\**\*.nupkg artifactType: container artifactName: Packages \ No newline at end of file From 61d190cbd342b001a56ef9e87ea01511ed500260 Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 11:14:47 -0500 Subject: [PATCH 02/10] Use manual shell invocation task for msbuild --- azure-pipelines.yml | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 482dcbe..fb6d4d3 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -47,19 +47,8 @@ steps: - powershell: .\build\Install-WindowsSdkISO.ps1 18362 -- task: DotNetCoreCLI@2 - displayName: NuGet restore - inputs: - command: custom - custom: msbuild - arguments: -p:Configuration=Release -t:restore .\ColorCode.sln - -- task: DotNetCoreCLI@2 +- script: msbuild -p:Configuration=Release -r -t:pack .\ColorCode.sln displayName: Build and pack - inputs: - command: custom - custom: msbuild - arguments: -p:Configuration=Release -t:pack .\ColorCode.sln - task: PowerShell@2 displayName: Authenticode Sign Packages From 41896bde6e0d67276265c5e1f296399d3a314597 Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:09:12 -0500 Subject: [PATCH 03/10] Copy nupkg to single folder before publishing artifacts --- azure-pipelines.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index fb6d4d3..07845f5 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -50,6 +50,11 @@ steps: - script: msbuild -p:Configuration=Release -r -t:pack .\ColorCode.sln displayName: Build and pack +- task: CopyFiles@2 + inputs: + Contents: '**\*.nupkg' + TargetFolder: 'build\nupkg' + - task: PowerShell@2 displayName: Authenticode Sign Packages inputs: @@ -63,6 +68,6 @@ steps: - task: PublishBuildArtifacts@1 displayName: Publish Package Artifacts inputs: - pathToPublish: .\**\*.nupkg + pathToPublish: 'build\nupkg' artifactType: container artifactName: Packages \ No newline at end of file From fc5e779fb70935b3df5e9f2751b95e274aa5b56f Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:17:56 -0500 Subject: [PATCH 04/10] Enable folder flattening when copying files --- azure-pipelines.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 07845f5..9007e7a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -54,6 +54,7 @@ steps: inputs: Contents: '**\*.nupkg' TargetFolder: 'build\nupkg' + flattenFolders: true - task: PowerShell@2 displayName: Authenticode Sign Packages From 8e770355cb58d0249e421693fac8cbc116ec0d07 Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:29:44 -0500 Subject: [PATCH 05/10] Only include ColorCode nupkg files --- azure-pipelines.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9007e7a..44d99ed 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -52,7 +52,7 @@ steps: - task: CopyFiles@2 inputs: - Contents: '**\*.nupkg' + Contents: '**\ColorCode.*.nupkg' TargetFolder: 'build\nupkg' flattenFolders: true From b67b4bbf7f370b80082fe266b5d187060e85244e Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:57:10 -0500 Subject: [PATCH 06/10] Removed cake --- ColorCode.sln | 1 - build/Build.bat | 3 - build/Find-WindowsSDKVersions.ps1 | 165 ------------------ build/Install-WindowsSdkISO.ps1 | 256 ---------------------------- build/Sign-Package.ps1 | 28 --- build/SignClientSettings.json | 13 -- build/UpdateHeaders.bat | 3 - build/build.cake | 177 ------------------- build/build.ps1 | 274 ------------------------------ build/header.txt | 3 - build/tools/packages.config | 4 - 11 files changed, 927 deletions(-) delete mode 100644 build/Build.bat delete mode 100644 build/Find-WindowsSDKVersions.ps1 delete mode 100644 build/Install-WindowsSdkISO.ps1 delete mode 100644 build/Sign-Package.ps1 delete mode 100644 build/SignClientSettings.json delete mode 100644 build/UpdateHeaders.bat delete mode 100644 build/build.cake delete mode 100644 build/build.ps1 delete mode 100644 build/header.txt delete mode 100644 build/tools/packages.config diff --git a/ColorCode.sln b/ColorCode.sln index 4365b2c..c8355f3 100644 --- a/ColorCode.sln +++ b/ColorCode.sln @@ -20,7 +20,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A4B1B99B-FC3A-4C76-8B46-B96723829FD2}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml - build\build.cake = build\build.cake ColorCode.snk = ColorCode.snk Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets diff --git a/build/Build.bat b/build/Build.bat deleted file mode 100644 index f541994..0000000 --- a/build/Build.bat +++ /dev/null @@ -1,3 +0,0 @@ -@ECHO OFF -PowerShell.exe -file build.ps1 -PAUSE \ No newline at end of file diff --git a/build/Find-WindowsSDKVersions.ps1 b/build/Find-WindowsSDKVersions.ps1 deleted file mode 100644 index b743dac..0000000 --- a/build/Find-WindowsSDKVersions.ps1 +++ /dev/null @@ -1,165 +0,0 @@ -$script:ns = 'http://schemas.microsoft.com/developer/msbuild/2003' - -$ErrorActionPreference = 'Stop' - -# Unique set of Windows SDK versions referenced in files -$versions = New-Object System.Collections.Generic.HashSet[System.String] - -function Get-Nodes -{ - param( - [parameter(ValueFromPipeline=$true)] - [xml] $xml, - [parameter(Mandatory=$true)] - [string] $nodeName) - - # Try the old style csproj. Also format required for .targets and .props files - $n = Select-Xml -Xml $xml.Project -Namespace @{d = $ns } -XPath "//d:$nodeName" - - # Try the SDK-style files - if (!$n) { - $r = Select-Xml -Xml $xml.Project -XPath "//$nodeName" - } - - return $r -} - -function Get-NodeValue -{ - param( - [parameter(ValueFromPipeline=$true)] - [xml] $xml, - [string] $nodeName) - - $node = get-nodes $xml $nodeName - - if ($node) { - if ($node.Node) { - return [string]$node.Node.'#text' - } - } - - return [string]"" -} - -function Get-SdkVersion -{ - param( - [Parameter(ValueFromPipeline=$true)] $file) - - [xml] $xml = Get-Content $file - - # If you want a complete set of SDKs that are required, uncomment the following - # $version = Get-NodeValue $xml 'PropertyGroup/TargetPlatformMinVersion' - # $versions.Add($version) | Out-Null - - $version = Get-NodeValue $xml 'PropertyGroup/TargetPlatformVersion' - $versions.Add($version) | Out-Null - - # Versions may also be specified without the 10.0.xxxxx.0 format in the - # PropertyGroup/DefaultTargetPlatformVersion and PropertyGroup/DefaultTargetPlatformMinVersion - - # If you want a complete set of SDKs that are required, uncomment the following - # $version = Get-NodeValue $xml 'PropertyGroup/DefaultTargetPlatformMinVersion' - # $versions.Add("10.0." + $version + ".0") | Out-Null - - $version = Get-NodeValue $xml 'PropertyGroup/DefaultTargetPlatformVersion' - $versions.Add("10.0." + $version + ".0") | Out-Null -} - -function Test-RegistryPathAndValue -{ - param ( - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string] $path, - [parameter(Mandatory=$true)] - [ValidateNotNullOrEmpty()] - [string] $value) - - try - { - if (Test-Path $path) - { - Get-ItemProperty -Path $path | Select-Object -ExpandProperty $value -ErrorAction Stop | Out-Null - return $true - } - } - catch - { - } - - return $false -} - -function Test-InstallWindowsSdk([string] $WindowsSDKVersion) { - $retval = $true - - $WindowsSDKRegPath = "HKLM:\Software\Microsoft\Windows Kits\Installed Roots" - $WindowsSDKRegRootKey = "KitsRoot10" - $WindowsSDKOptions = @("OptionId.UWPCpp") - - $WindowsSDKInstalledRegPath = "$WindowsSDKRegPath\$WindowsSDKVersion\Installed Options" - - if (Test-RegistryPathAndValue -Path $WindowsSDKRegPath -Value $WindowsSDKRegRootKey) - { - # A Windows SDK is installed - # Is an SDK of our version installed with the options we need? - if (Test-RegistryPathAndValue -Path $WindowsSDKInstalledRegPath -Value "$WindowsSDKOptions") - { - # It appears we have what we need. Double check the disk - $sdkRoot = Get-ItemProperty -Path $WindowsSDKRegPath | Select-Object -ExpandProperty $WindowsSDKRegRootKey - if ($sdkRoot) - { - if (Test-Path $sdkRoot) - { - $refPath = Join-Path $sdkRoot "References\$WindowsSDKVersion" - if (Test-Path $refPath) - { - $umdPath = Join-Path $sdkRoot "UnionMetadata\$WindowsSDKVersion" - if (Test-Path $umdPath) - { - # Pretty sure we have what we need - $retval = $false - } - } - } - } - } - } - - return $retval -} - -if(!$PSScriptRoot){ - $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent -} - -Write-Host -NoNewline "Locating referenced Windows SDK versions..." - -Get-ChildItem *.csproj -Recurse | ForEach-Object { get-sdkversion $_} -Get-ChildItem *.targets -Recurse | ForEach-Object { get-sdkversion $_ } -Get-ChildItem *.props -Recurse | ForEach-Object { get-sdkversion $_ } - -Write-Host "Done" -Write-Host - -$anyInstallRequired = $false; - -foreach($version in $versions) { - if ($version -match "10\.0\.\d{5}\.0") { - $installRequired = Test-InstallWindowsSDK $version - Write-Host "Windows SDK '$version' install required: $installRequired" - if ($installRequired) { - # Automatically invoke Install-WindowsSDKIso.ps1 ? - $anyInstallRequired = $true - } - } -} - -Write-Host -if ($anyInstallRequired) { - throw "At least one Windows SDK is missing from this machine" -} else { - Write-Host "All referenced Windows SDKs are installed!" -} \ No newline at end of file diff --git a/build/Install-WindowsSdkISO.ps1 b/build/Install-WindowsSdkISO.ps1 deleted file mode 100644 index b83a3de..0000000 --- a/build/Install-WindowsSdkISO.ps1 +++ /dev/null @@ -1,256 +0,0 @@ -[CmdletBinding()] -param([Parameter(Mandatory = $true)] - [string]$buildNumber) - -# Ensure the error action preference is set to the default for PowerShell3, 'Stop' -$ErrorActionPreference = 'Stop' - -# Constants -$WindowsSDKOptions = @("OptionId.UWPCpp") -$WindowsSDKRegPath = "HKLM:\Software\Microsoft\Windows Kits\Installed Roots" -$WindowsSDKRegRootKey = "KitsRoot10" -$WindowsSDKVersion = "10.0.$buildNumber.0" -$WindowsSDKInstalledRegPath = "$WindowsSDKRegPath\$WindowsSDKVersion\Installed Options" -$StrongNameRegPath = "HKLM:\SOFTWARE\Microsoft\StrongName\Verification" -$PublicKeyTokens = @("31bf3856ad364e35") - -function Download-File { - param ([string] $outDir, - [string] $downloadUrl, - [string] $downloadName) - - $downloadPath = Join-Path $outDir "$downloadName.download" - $downloadDest = Join-Path $outDir $downloadName - $downloadDestTemp = Join-Path $outDir "$downloadName.tmp" - - Write-Host -NoNewline "Downloading $downloadName..." - - try { - $webclient = new-object System.Net.WebClient - $webclient.DownloadFile($downloadUrl, $downloadPath) - } - catch [System.Net.WebException] { - Write-Host - Write-Warning "Failed to fetch updated file from $downloadUrl" - if (!(Test-Path $downloadDest)) { - throw "$downloadName was not found at $downloadDest" - } - else { - Write-Warning "$downloadName may be out of date" - } - } - - Unblock-File $downloadPath - - $downloadDestTemp = $downloadPath; - - # Delete and rename to final dest - if (Test-Path -PathType Container $downloadDest) { - [System.IO.Directory]::Delete($downloadDest, $true) - } - - Move-Item -Force $downloadDestTemp $downloadDest - Write-Host "Done" - - return $downloadDest -} - -function Get-ISODriveLetter { - param ([string] $isoPath) - - $diskImage = Get-DiskImage -ImagePath $isoPath - if ($diskImage) { - $volume = Get-Volume -DiskImage $diskImage - - if ($volume) { - $driveLetter = $volume.DriveLetter - if ($driveLetter) { - $driveLetter += ":" - return $driveLetter - } - } - } - - return $null -} - -function Mount-ISO { - param ([string] $isoPath) - - # Check if image is already mounted - $isoDrive = Get-ISODriveLetter $isoPath - - if (!$isoDrive) { - Mount-DiskImage -ImagePath $isoPath -StorageType ISO | Out-Null - } - - $isoDrive = Get-ISODriveLetter $isoPath - Write-Verbose "$isoPath mounted to ${isoDrive}:" -} - -function Dismount-ISO { - param ([string] $isoPath) - - $isoDrive = (Get-DiskImage -ImagePath $isoPath | Get-Volume).DriveLetter - - if ($isoDrive) { - Write-Verbose "$isoPath dismounted" - Dismount-DiskImage -ImagePath $isoPath | Out-Null - } -} - -function Disable-StrongName { - param ([string] $publicKeyToken = "*") - - reg ADD "HKLM\SOFTWARE\Microsoft\StrongName\Verification\*,$publicKeyToken" /f | Out-Null - if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") { - reg ADD "HKLM\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification\*,$publicKeyToken" /f | Out-Null - } -} - -function Test-Admin { - $identity = [Security.Principal.WindowsIdentity]::GetCurrent() - $principal = New-Object Security.Principal.WindowsPrincipal $identity - $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -} - -function Test-RegistryPathAndValue { - param ( - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string] $path, - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [string] $value) - - try { - if (Test-Path $path) { - Get-ItemProperty -Path $path | Select-Object -ExpandProperty $value -ErrorAction Stop | Out-Null - return $true - } - } - catch { - } - - return $false -} - -function Test-InstallWindowsSDK { - $retval = $true - - if (Test-RegistryPathAndValue -Path $WindowsSDKRegPath -Value $WindowsSDKRegRootKey) { - # A Windows SDK is installed - # Is an SDK of our version installed with the options we need? - if (Test-RegistryPathAndValue -Path $WindowsSDKInstalledRegPath -Value "$WindowsSDKOptions") { - # It appears we have what we need. Double check the disk - $sdkRoot = Get-ItemProperty -Path $WindowsSDKRegPath | Select-Object -ExpandProperty $WindowsSDKRegRootKey - if ($sdkRoot) { - if (Test-Path $sdkRoot) { - $refPath = Join-Path $sdkRoot "References\$WindowsSDKVersion" - if (Test-Path $refPath) { - $umdPath = Join-Path $sdkRoot "UnionMetadata\$WindowsSDKVersion" - if (Test-Path $umdPath) { - # Pretty sure we have what we need - $retval = $false - } - } - } - } - } - } - - return $retval -} - -function Test-InstallStrongNameHijack { - foreach ($publicKeyToken in $PublicKeyTokens) { - $key = "$StrongNameRegPath\*,$publicKeyToken" - if (!(Test-Path $key)) { - return $true - } - } - - return $false -} - -Write-Host -NoNewline "Checking for installed Windows SDK $WindowsSDKVersion..." -$InstallWindowsSDK = Test-InstallWindowsSDK -if ($InstallWindowsSDK) { - Write-Host "Installation required" -} -else { - Write-Host "INSTALLED" -} - -$StrongNameHijack = Test-InstallStrongNameHijack -Write-Host -NoNewline "Checking if StrongName bypass required..." - -if ($StrongNameHijack) { - Write-Host "REQUIRED" -} -else { - Write-Host "Done" -} - -if ($StrongNameHijack -or $InstallWindowsSDK) { - if (!(Test-Admin)) { - Write-Host - throw "ERROR: Elevation required" - } -} - -if ($InstallWindowsSDK) { - # Static(ish) link for Windows SDK - # Note: there is a delay from Windows SDK announcements to availability via the static link - $uri = "https://software-download.microsoft.com/download/sg/Windows_InsiderPreview_SDK_en-us_$($buildNumber)_1.iso"; - - if ($null -eq $env:TEMP) { - $env:TEMP = Join-Path $env:SystemDrive 'temp' - } - - $winsdkTempDir = Join-Path $env:TEMP "WindowsSDK" - - if (![System.IO.Directory]::Exists($winsdkTempDir)) { - [void][System.IO.Directory]::CreateDirectory($winsdkTempDir) - } - - $file = "winsdk_$buildNumber.iso" - - Write-Verbose "Getting WinSDK from $uri" - $downloadFile = Download-File $winsdkTempDir $uri $file - - # TODO Check if zip, exe, iso, etc. - try { - Write-Host -NoNewline "Mounting ISO $file..." - Mount-ISO $downloadFile - Write-Host "Done" - - $isoDrive = Get-ISODriveLetter $downloadFile - - if (Test-Path $isoDrive) { - Write-Host -NoNewLine "Installing WinSDK..." - - $setupPath = Join-Path "$isoDrive" "WinSDKSetup.exe" - Start-Process -Wait $setupPath "/features $WindowsSDKOptions /q" - Write-Host "Done" - } - else { - throw "Could not find mounted ISO at ${isoDrive}" - } - } - finally { - Write-Host -NoNewline "Dismounting ISO $file..." - # Dismount-ISO $downloadFile - Write-Host "Done" - } -} - -if ($StrongNameHijack) { - Write-Host -NoNewline "Disabling StrongName for Windows SDK..." - - foreach ($key in $PublicKeyTokens) { - Disable-StrongName $key - } - - Write-Host "Done" -} \ No newline at end of file diff --git a/build/Sign-Package.ps1 b/build/Sign-Package.ps1 deleted file mode 100644 index b1f5360..0000000 --- a/build/Sign-Package.ps1 +++ /dev/null @@ -1,28 +0,0 @@ - -$currentDirectory = split-path $MyInvocation.MyCommand.Definition - -# See if we have the ClientSecret available -if([string]::IsNullOrEmpty($Env:SignClientSecret)){ - Write-Host "Client Secret not found, not signing packages" - return; -} - -dotnet tool install --tool-path . SignClient - -# Setup Variables we need to pass into the sign client tool - -$appSettings = "$currentDirectory\SignClientSettings.json" - -$nupkgs = gci $Env:ArtifactDirectory\*.nupkg -recurse | Select -ExpandProperty FullName - -foreach ($nupkg in $nupkgs){ - Write-Host "Submitting $nupkg for signing" - - .\SignClient 'sign' -c $appSettings -i $nupkg -r $Env:SignClientUser -s $Env:SignClientSecret -n 'Windows Community Toolkit' -d 'Windows Community Toolkit' -u 'https://developer.microsoft.com/en-us/windows/uwp-community-toolkit' - if ($LASTEXITCODE -ne 0) { - exit 1 - } - Write-Host "Finished signing $nupkg" -} - -Write-Host "Sign-package complete" \ No newline at end of file diff --git a/build/SignClientSettings.json b/build/SignClientSettings.json deleted file mode 100644 index 3276a45..0000000 --- a/build/SignClientSettings.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "SignClient": { - "AzureAd": { - "AADInstance": "https://login.microsoftonline.com/", - "ClientId": "c248d68a-ba6f-4aa9-8a68-71fe872063f8", - "TenantId": "16076fdc-fcc1-4a15-b1ca-32c9a255900e" - }, - "Service": { - "Url": "https://codesign.dotnetfoundation.org/", - "ResourceId": "https://SignService/3c30251f-36f3-490b-a955-520addb85001" - } - } -} \ No newline at end of file diff --git a/build/UpdateHeaders.bat b/build/UpdateHeaders.bat deleted file mode 100644 index 5587277..0000000 --- a/build/UpdateHeaders.bat +++ /dev/null @@ -1,3 +0,0 @@ -@ECHO OFF -PowerShell.exe -file "%~dp0build.ps1" -Target UpdateHeaders -PAUSE \ No newline at end of file diff --git a/build/build.cake b/build/build.cake deleted file mode 100644 index 2c085d7..0000000 --- a/build/build.cake +++ /dev/null @@ -1,177 +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.244 - -#tool nuget:?package=vswhere&version=2.8.4 - -using System; -using System.Linq; -using System.Text.RegularExpressions; - -////////////////////////////////////////////////////////////////////// -// ARGUMENTS -////////////////////////////////////////////////////////////////////// - -var target = Argument("target", "Default"); - -////////////////////////////////////////////////////////////////////// -// PREPARATION -////////////////////////////////////////////////////////////////////// - -var baseDir = MakeAbsolute(Directory("../")).ToString(); -var buildDir = baseDir + "/build"; - -var Solution = baseDir + "/ColorCode.sln"; -var nupkgDir = buildDir + "/nupkg"; - -string Version = null; - -////////////////////////////////////////////////////////////////////// -// METHODS -////////////////////////////////////////////////////////////////////// - -void VerifyHeaders(bool Replace) -{ - var header = FileReadText("header.txt") + "\r\n"; - bool hasMissing = false; - - Func 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("// ")) - { - 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."); - } -} - -void RetrieveVersion() -{ - Information("\nRetrieving version..."); - Version = GitVersioningGetVersion().NuGetPackageVersion; - Information("\nBuild Version: " + Version); -} - -void UpdateToolsPath(MSBuildSettings buildSettings) -{ - // Workaround for https://github.com/cake-build/cake/issues/2128 - var vsInstallation = VSWhereLatest(new VSWhereLatestSettings { Requires = "Microsoft.Component.MSBuild", IncludePrerelease = false }); - - if (vsInstallation != null) - { - buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\Current\Bin\MSBuild.exe"); - if (!FileExists(buildSettings.ToolPath)) - buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\15.0\Bin\MSBuild.exe"); - } -} - -////////////////////////////////////////////////////////////////////// -// TASKS -////////////////////////////////////////////////////////////////////// - -Task("Clean") - .Does(() => -{ - Information("\nCleaning Package Directory"); - CleanDirectory(nupkgDir); -}); - -Task("Restore-NuGet-Packages") - .IsDependentOn("Clean") - .Does(() => -{ - DotNetCoreRestore(Solution); -}); - -Task("Verify") - .Description("Run pre-build verifications") - .IsDependentOn("Clean") - .Does(() => -{ - VerifyHeaders(false); - - StartPowershellFile("./Find-WindowsSDKVersions.ps1"); -}); - -Task("Version") - .Description("Updates the version information in all Projects") - .IsDependentOn("Verify") - .IsDependentOn("Restore-NuGet-Packages") - .Does(() => -{ - RetrieveVersion(); -}); - -Task("Build") - .IsDependentOn("Version") - .Does(() => -{ - Information("\nBuilding Solution"); - var buildSettings = new MSBuildSettings - { - MaxCpuCount = 0 - } - .SetConfiguration("Release") - .WithTarget("Pack") - .WithProperty("GenerateLibraryLayout", "true") - .WithProperty("PackageOutputPath", nupkgDir); - - UpdateToolsPath(buildSettings); - - EnsureDirectoryExists(nupkgDir); - - MSBuild(Solution, buildSettings); -}); - -////////////////////////////////////////////////////////////////////// -// TASK TARGETS -////////////////////////////////////////////////////////////////////// - -Task("Default") - .IsDependentOn("Build"); - -Task("UpdateHeaders") - .Description("Updates the headers in *.cs files") - .Does(() => -{ - VerifyHeaders(true); -}); - -////////////////////////////////////////////////////////////////////// -// EXECUTION -////////////////////////////////////////////////////////////////////// - -RunTarget(target); diff --git a/build/build.ps1 b/build/build.ps1 deleted file mode 100644 index 2636495..0000000 --- a/build/build.ps1 +++ /dev/null @@ -1,274 +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 ($file -ne $null) - { - $file.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 ($NUGET_EXE_IN_PATH -ne $null -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 " ")" -exit $LASTEXITCODE \ No newline at end of file diff --git a/build/header.txt b/build/header.txt deleted file mode 100644 index 45274ba..0000000 --- a/build/header.txt +++ /dev/null @@ -1,3 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. diff --git a/build/tools/packages.config b/build/tools/packages.config deleted file mode 100644 index 2a03746..0000000 --- a/build/tools/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - From cd4cea10109ca372ad2b5c12d1ac77a492ea70bc Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:58:25 -0500 Subject: [PATCH 07/10] Revert "Removed cake" This reverts commit b67b4bbf7f370b80082fe266b5d187060e85244e. --- ColorCode.sln | 1 + build/Build.bat | 3 + build/Find-WindowsSDKVersions.ps1 | 165 ++++++++++++++++++ build/Install-WindowsSdkISO.ps1 | 256 ++++++++++++++++++++++++++++ build/Sign-Package.ps1 | 28 +++ build/SignClientSettings.json | 13 ++ build/UpdateHeaders.bat | 3 + build/build.cake | 177 +++++++++++++++++++ build/build.ps1 | 274 ++++++++++++++++++++++++++++++ build/header.txt | 3 + build/tools/packages.config | 4 + 11 files changed, 927 insertions(+) create mode 100644 build/Build.bat create mode 100644 build/Find-WindowsSDKVersions.ps1 create mode 100644 build/Install-WindowsSdkISO.ps1 create mode 100644 build/Sign-Package.ps1 create mode 100644 build/SignClientSettings.json create mode 100644 build/UpdateHeaders.bat create mode 100644 build/build.cake create mode 100644 build/build.ps1 create mode 100644 build/header.txt create mode 100644 build/tools/packages.config diff --git a/ColorCode.sln b/ColorCode.sln index c8355f3..4365b2c 100644 --- a/ColorCode.sln +++ b/ColorCode.sln @@ -20,6 +20,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A4B1B99B-FC3A-4C76-8B46-B96723829FD2}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml + build\build.cake = build\build.cake ColorCode.snk = ColorCode.snk Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets diff --git a/build/Build.bat b/build/Build.bat new file mode 100644 index 0000000..f541994 --- /dev/null +++ b/build/Build.bat @@ -0,0 +1,3 @@ +@ECHO OFF +PowerShell.exe -file build.ps1 +PAUSE \ No newline at end of file diff --git a/build/Find-WindowsSDKVersions.ps1 b/build/Find-WindowsSDKVersions.ps1 new file mode 100644 index 0000000..b743dac --- /dev/null +++ b/build/Find-WindowsSDKVersions.ps1 @@ -0,0 +1,165 @@ +$script:ns = 'http://schemas.microsoft.com/developer/msbuild/2003' + +$ErrorActionPreference = 'Stop' + +# Unique set of Windows SDK versions referenced in files +$versions = New-Object System.Collections.Generic.HashSet[System.String] + +function Get-Nodes +{ + param( + [parameter(ValueFromPipeline=$true)] + [xml] $xml, + [parameter(Mandatory=$true)] + [string] $nodeName) + + # Try the old style csproj. Also format required for .targets and .props files + $n = Select-Xml -Xml $xml.Project -Namespace @{d = $ns } -XPath "//d:$nodeName" + + # Try the SDK-style files + if (!$n) { + $r = Select-Xml -Xml $xml.Project -XPath "//$nodeName" + } + + return $r +} + +function Get-NodeValue +{ + param( + [parameter(ValueFromPipeline=$true)] + [xml] $xml, + [string] $nodeName) + + $node = get-nodes $xml $nodeName + + if ($node) { + if ($node.Node) { + return [string]$node.Node.'#text' + } + } + + return [string]"" +} + +function Get-SdkVersion +{ + param( + [Parameter(ValueFromPipeline=$true)] $file) + + [xml] $xml = Get-Content $file + + # If you want a complete set of SDKs that are required, uncomment the following + # $version = Get-NodeValue $xml 'PropertyGroup/TargetPlatformMinVersion' + # $versions.Add($version) | Out-Null + + $version = Get-NodeValue $xml 'PropertyGroup/TargetPlatformVersion' + $versions.Add($version) | Out-Null + + # Versions may also be specified without the 10.0.xxxxx.0 format in the + # PropertyGroup/DefaultTargetPlatformVersion and PropertyGroup/DefaultTargetPlatformMinVersion + + # If you want a complete set of SDKs that are required, uncomment the following + # $version = Get-NodeValue $xml 'PropertyGroup/DefaultTargetPlatformMinVersion' + # $versions.Add("10.0." + $version + ".0") | Out-Null + + $version = Get-NodeValue $xml 'PropertyGroup/DefaultTargetPlatformVersion' + $versions.Add("10.0." + $version + ".0") | Out-Null +} + +function Test-RegistryPathAndValue +{ + param ( + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string] $path, + [parameter(Mandatory=$true)] + [ValidateNotNullOrEmpty()] + [string] $value) + + try + { + if (Test-Path $path) + { + Get-ItemProperty -Path $path | Select-Object -ExpandProperty $value -ErrorAction Stop | Out-Null + return $true + } + } + catch + { + } + + return $false +} + +function Test-InstallWindowsSdk([string] $WindowsSDKVersion) { + $retval = $true + + $WindowsSDKRegPath = "HKLM:\Software\Microsoft\Windows Kits\Installed Roots" + $WindowsSDKRegRootKey = "KitsRoot10" + $WindowsSDKOptions = @("OptionId.UWPCpp") + + $WindowsSDKInstalledRegPath = "$WindowsSDKRegPath\$WindowsSDKVersion\Installed Options" + + if (Test-RegistryPathAndValue -Path $WindowsSDKRegPath -Value $WindowsSDKRegRootKey) + { + # A Windows SDK is installed + # Is an SDK of our version installed with the options we need? + if (Test-RegistryPathAndValue -Path $WindowsSDKInstalledRegPath -Value "$WindowsSDKOptions") + { + # It appears we have what we need. Double check the disk + $sdkRoot = Get-ItemProperty -Path $WindowsSDKRegPath | Select-Object -ExpandProperty $WindowsSDKRegRootKey + if ($sdkRoot) + { + if (Test-Path $sdkRoot) + { + $refPath = Join-Path $sdkRoot "References\$WindowsSDKVersion" + if (Test-Path $refPath) + { + $umdPath = Join-Path $sdkRoot "UnionMetadata\$WindowsSDKVersion" + if (Test-Path $umdPath) + { + # Pretty sure we have what we need + $retval = $false + } + } + } + } + } + } + + return $retval +} + +if(!$PSScriptRoot){ + $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent +} + +Write-Host -NoNewline "Locating referenced Windows SDK versions..." + +Get-ChildItem *.csproj -Recurse | ForEach-Object { get-sdkversion $_} +Get-ChildItem *.targets -Recurse | ForEach-Object { get-sdkversion $_ } +Get-ChildItem *.props -Recurse | ForEach-Object { get-sdkversion $_ } + +Write-Host "Done" +Write-Host + +$anyInstallRequired = $false; + +foreach($version in $versions) { + if ($version -match "10\.0\.\d{5}\.0") { + $installRequired = Test-InstallWindowsSDK $version + Write-Host "Windows SDK '$version' install required: $installRequired" + if ($installRequired) { + # Automatically invoke Install-WindowsSDKIso.ps1 ? + $anyInstallRequired = $true + } + } +} + +Write-Host +if ($anyInstallRequired) { + throw "At least one Windows SDK is missing from this machine" +} else { + Write-Host "All referenced Windows SDKs are installed!" +} \ No newline at end of file diff --git a/build/Install-WindowsSdkISO.ps1 b/build/Install-WindowsSdkISO.ps1 new file mode 100644 index 0000000..b83a3de --- /dev/null +++ b/build/Install-WindowsSdkISO.ps1 @@ -0,0 +1,256 @@ +[CmdletBinding()] +param([Parameter(Mandatory = $true)] + [string]$buildNumber) + +# Ensure the error action preference is set to the default for PowerShell3, 'Stop' +$ErrorActionPreference = 'Stop' + +# Constants +$WindowsSDKOptions = @("OptionId.UWPCpp") +$WindowsSDKRegPath = "HKLM:\Software\Microsoft\Windows Kits\Installed Roots" +$WindowsSDKRegRootKey = "KitsRoot10" +$WindowsSDKVersion = "10.0.$buildNumber.0" +$WindowsSDKInstalledRegPath = "$WindowsSDKRegPath\$WindowsSDKVersion\Installed Options" +$StrongNameRegPath = "HKLM:\SOFTWARE\Microsoft\StrongName\Verification" +$PublicKeyTokens = @("31bf3856ad364e35") + +function Download-File { + param ([string] $outDir, + [string] $downloadUrl, + [string] $downloadName) + + $downloadPath = Join-Path $outDir "$downloadName.download" + $downloadDest = Join-Path $outDir $downloadName + $downloadDestTemp = Join-Path $outDir "$downloadName.tmp" + + Write-Host -NoNewline "Downloading $downloadName..." + + try { + $webclient = new-object System.Net.WebClient + $webclient.DownloadFile($downloadUrl, $downloadPath) + } + catch [System.Net.WebException] { + Write-Host + Write-Warning "Failed to fetch updated file from $downloadUrl" + if (!(Test-Path $downloadDest)) { + throw "$downloadName was not found at $downloadDest" + } + else { + Write-Warning "$downloadName may be out of date" + } + } + + Unblock-File $downloadPath + + $downloadDestTemp = $downloadPath; + + # Delete and rename to final dest + if (Test-Path -PathType Container $downloadDest) { + [System.IO.Directory]::Delete($downloadDest, $true) + } + + Move-Item -Force $downloadDestTemp $downloadDest + Write-Host "Done" + + return $downloadDest +} + +function Get-ISODriveLetter { + param ([string] $isoPath) + + $diskImage = Get-DiskImage -ImagePath $isoPath + if ($diskImage) { + $volume = Get-Volume -DiskImage $diskImage + + if ($volume) { + $driveLetter = $volume.DriveLetter + if ($driveLetter) { + $driveLetter += ":" + return $driveLetter + } + } + } + + return $null +} + +function Mount-ISO { + param ([string] $isoPath) + + # Check if image is already mounted + $isoDrive = Get-ISODriveLetter $isoPath + + if (!$isoDrive) { + Mount-DiskImage -ImagePath $isoPath -StorageType ISO | Out-Null + } + + $isoDrive = Get-ISODriveLetter $isoPath + Write-Verbose "$isoPath mounted to ${isoDrive}:" +} + +function Dismount-ISO { + param ([string] $isoPath) + + $isoDrive = (Get-DiskImage -ImagePath $isoPath | Get-Volume).DriveLetter + + if ($isoDrive) { + Write-Verbose "$isoPath dismounted" + Dismount-DiskImage -ImagePath $isoPath | Out-Null + } +} + +function Disable-StrongName { + param ([string] $publicKeyToken = "*") + + reg ADD "HKLM\SOFTWARE\Microsoft\StrongName\Verification\*,$publicKeyToken" /f | Out-Null + if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") { + reg ADD "HKLM\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification\*,$publicKeyToken" /f | Out-Null + } +} + +function Test-Admin { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal $identity + $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +function Test-RegistryPathAndValue { + param ( + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string] $path, + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string] $value) + + try { + if (Test-Path $path) { + Get-ItemProperty -Path $path | Select-Object -ExpandProperty $value -ErrorAction Stop | Out-Null + return $true + } + } + catch { + } + + return $false +} + +function Test-InstallWindowsSDK { + $retval = $true + + if (Test-RegistryPathAndValue -Path $WindowsSDKRegPath -Value $WindowsSDKRegRootKey) { + # A Windows SDK is installed + # Is an SDK of our version installed with the options we need? + if (Test-RegistryPathAndValue -Path $WindowsSDKInstalledRegPath -Value "$WindowsSDKOptions") { + # It appears we have what we need. Double check the disk + $sdkRoot = Get-ItemProperty -Path $WindowsSDKRegPath | Select-Object -ExpandProperty $WindowsSDKRegRootKey + if ($sdkRoot) { + if (Test-Path $sdkRoot) { + $refPath = Join-Path $sdkRoot "References\$WindowsSDKVersion" + if (Test-Path $refPath) { + $umdPath = Join-Path $sdkRoot "UnionMetadata\$WindowsSDKVersion" + if (Test-Path $umdPath) { + # Pretty sure we have what we need + $retval = $false + } + } + } + } + } + } + + return $retval +} + +function Test-InstallStrongNameHijack { + foreach ($publicKeyToken in $PublicKeyTokens) { + $key = "$StrongNameRegPath\*,$publicKeyToken" + if (!(Test-Path $key)) { + return $true + } + } + + return $false +} + +Write-Host -NoNewline "Checking for installed Windows SDK $WindowsSDKVersion..." +$InstallWindowsSDK = Test-InstallWindowsSDK +if ($InstallWindowsSDK) { + Write-Host "Installation required" +} +else { + Write-Host "INSTALLED" +} + +$StrongNameHijack = Test-InstallStrongNameHijack +Write-Host -NoNewline "Checking if StrongName bypass required..." + +if ($StrongNameHijack) { + Write-Host "REQUIRED" +} +else { + Write-Host "Done" +} + +if ($StrongNameHijack -or $InstallWindowsSDK) { + if (!(Test-Admin)) { + Write-Host + throw "ERROR: Elevation required" + } +} + +if ($InstallWindowsSDK) { + # Static(ish) link for Windows SDK + # Note: there is a delay from Windows SDK announcements to availability via the static link + $uri = "https://software-download.microsoft.com/download/sg/Windows_InsiderPreview_SDK_en-us_$($buildNumber)_1.iso"; + + if ($null -eq $env:TEMP) { + $env:TEMP = Join-Path $env:SystemDrive 'temp' + } + + $winsdkTempDir = Join-Path $env:TEMP "WindowsSDK" + + if (![System.IO.Directory]::Exists($winsdkTempDir)) { + [void][System.IO.Directory]::CreateDirectory($winsdkTempDir) + } + + $file = "winsdk_$buildNumber.iso" + + Write-Verbose "Getting WinSDK from $uri" + $downloadFile = Download-File $winsdkTempDir $uri $file + + # TODO Check if zip, exe, iso, etc. + try { + Write-Host -NoNewline "Mounting ISO $file..." + Mount-ISO $downloadFile + Write-Host "Done" + + $isoDrive = Get-ISODriveLetter $downloadFile + + if (Test-Path $isoDrive) { + Write-Host -NoNewLine "Installing WinSDK..." + + $setupPath = Join-Path "$isoDrive" "WinSDKSetup.exe" + Start-Process -Wait $setupPath "/features $WindowsSDKOptions /q" + Write-Host "Done" + } + else { + throw "Could not find mounted ISO at ${isoDrive}" + } + } + finally { + Write-Host -NoNewline "Dismounting ISO $file..." + # Dismount-ISO $downloadFile + Write-Host "Done" + } +} + +if ($StrongNameHijack) { + Write-Host -NoNewline "Disabling StrongName for Windows SDK..." + + foreach ($key in $PublicKeyTokens) { + Disable-StrongName $key + } + + Write-Host "Done" +} \ No newline at end of file diff --git a/build/Sign-Package.ps1 b/build/Sign-Package.ps1 new file mode 100644 index 0000000..b1f5360 --- /dev/null +++ b/build/Sign-Package.ps1 @@ -0,0 +1,28 @@ + +$currentDirectory = split-path $MyInvocation.MyCommand.Definition + +# See if we have the ClientSecret available +if([string]::IsNullOrEmpty($Env:SignClientSecret)){ + Write-Host "Client Secret not found, not signing packages" + return; +} + +dotnet tool install --tool-path . SignClient + +# Setup Variables we need to pass into the sign client tool + +$appSettings = "$currentDirectory\SignClientSettings.json" + +$nupkgs = gci $Env:ArtifactDirectory\*.nupkg -recurse | Select -ExpandProperty FullName + +foreach ($nupkg in $nupkgs){ + Write-Host "Submitting $nupkg for signing" + + .\SignClient 'sign' -c $appSettings -i $nupkg -r $Env:SignClientUser -s $Env:SignClientSecret -n 'Windows Community Toolkit' -d 'Windows Community Toolkit' -u 'https://developer.microsoft.com/en-us/windows/uwp-community-toolkit' + if ($LASTEXITCODE -ne 0) { + exit 1 + } + Write-Host "Finished signing $nupkg" +} + +Write-Host "Sign-package complete" \ No newline at end of file diff --git a/build/SignClientSettings.json b/build/SignClientSettings.json new file mode 100644 index 0000000..3276a45 --- /dev/null +++ b/build/SignClientSettings.json @@ -0,0 +1,13 @@ +{ + "SignClient": { + "AzureAd": { + "AADInstance": "https://login.microsoftonline.com/", + "ClientId": "c248d68a-ba6f-4aa9-8a68-71fe872063f8", + "TenantId": "16076fdc-fcc1-4a15-b1ca-32c9a255900e" + }, + "Service": { + "Url": "https://codesign.dotnetfoundation.org/", + "ResourceId": "https://SignService/3c30251f-36f3-490b-a955-520addb85001" + } + } +} \ No newline at end of file diff --git a/build/UpdateHeaders.bat b/build/UpdateHeaders.bat new file mode 100644 index 0000000..5587277 --- /dev/null +++ b/build/UpdateHeaders.bat @@ -0,0 +1,3 @@ +@ECHO OFF +PowerShell.exe -file "%~dp0build.ps1" -Target UpdateHeaders +PAUSE \ No newline at end of file diff --git a/build/build.cake b/build/build.cake new file mode 100644 index 0000000..2c085d7 --- /dev/null +++ b/build/build.cake @@ -0,0 +1,177 @@ +#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.244 + +#tool nuget:?package=vswhere&version=2.8.4 + +using System; +using System.Linq; +using System.Text.RegularExpressions; + +////////////////////////////////////////////////////////////////////// +// ARGUMENTS +////////////////////////////////////////////////////////////////////// + +var target = Argument("target", "Default"); + +////////////////////////////////////////////////////////////////////// +// PREPARATION +////////////////////////////////////////////////////////////////////// + +var baseDir = MakeAbsolute(Directory("../")).ToString(); +var buildDir = baseDir + "/build"; + +var Solution = baseDir + "/ColorCode.sln"; +var nupkgDir = buildDir + "/nupkg"; + +string Version = null; + +////////////////////////////////////////////////////////////////////// +// METHODS +////////////////////////////////////////////////////////////////////// + +void VerifyHeaders(bool Replace) +{ + var header = FileReadText("header.txt") + "\r\n"; + bool hasMissing = false; + + Func 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("// ")) + { + 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."); + } +} + +void RetrieveVersion() +{ + Information("\nRetrieving version..."); + Version = GitVersioningGetVersion().NuGetPackageVersion; + Information("\nBuild Version: " + Version); +} + +void UpdateToolsPath(MSBuildSettings buildSettings) +{ + // Workaround for https://github.com/cake-build/cake/issues/2128 + var vsInstallation = VSWhereLatest(new VSWhereLatestSettings { Requires = "Microsoft.Component.MSBuild", IncludePrerelease = false }); + + if (vsInstallation != null) + { + buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\Current\Bin\MSBuild.exe"); + if (!FileExists(buildSettings.ToolPath)) + buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\15.0\Bin\MSBuild.exe"); + } +} + +////////////////////////////////////////////////////////////////////// +// TASKS +////////////////////////////////////////////////////////////////////// + +Task("Clean") + .Does(() => +{ + Information("\nCleaning Package Directory"); + CleanDirectory(nupkgDir); +}); + +Task("Restore-NuGet-Packages") + .IsDependentOn("Clean") + .Does(() => +{ + DotNetCoreRestore(Solution); +}); + +Task("Verify") + .Description("Run pre-build verifications") + .IsDependentOn("Clean") + .Does(() => +{ + VerifyHeaders(false); + + StartPowershellFile("./Find-WindowsSDKVersions.ps1"); +}); + +Task("Version") + .Description("Updates the version information in all Projects") + .IsDependentOn("Verify") + .IsDependentOn("Restore-NuGet-Packages") + .Does(() => +{ + RetrieveVersion(); +}); + +Task("Build") + .IsDependentOn("Version") + .Does(() => +{ + Information("\nBuilding Solution"); + var buildSettings = new MSBuildSettings + { + MaxCpuCount = 0 + } + .SetConfiguration("Release") + .WithTarget("Pack") + .WithProperty("GenerateLibraryLayout", "true") + .WithProperty("PackageOutputPath", nupkgDir); + + UpdateToolsPath(buildSettings); + + EnsureDirectoryExists(nupkgDir); + + MSBuild(Solution, buildSettings); +}); + +////////////////////////////////////////////////////////////////////// +// TASK TARGETS +////////////////////////////////////////////////////////////////////// + +Task("Default") + .IsDependentOn("Build"); + +Task("UpdateHeaders") + .Description("Updates the headers in *.cs files") + .Does(() => +{ + VerifyHeaders(true); +}); + +////////////////////////////////////////////////////////////////////// +// EXECUTION +////////////////////////////////////////////////////////////////////// + +RunTarget(target); diff --git a/build/build.ps1 b/build/build.ps1 new file mode 100644 index 0000000..2636495 --- /dev/null +++ b/build/build.ps1 @@ -0,0 +1,274 @@ +########################################################################## +# 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 ($file -ne $null) + { + $file.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 ($NUGET_EXE_IN_PATH -ne $null -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 " ")" +exit $LASTEXITCODE \ No newline at end of file diff --git a/build/header.txt b/build/header.txt new file mode 100644 index 0000000..45274ba --- /dev/null +++ b/build/header.txt @@ -0,0 +1,3 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. diff --git a/build/tools/packages.config b/build/tools/packages.config new file mode 100644 index 0000000..2a03746 --- /dev/null +++ b/build/tools/packages.config @@ -0,0 +1,4 @@ + + + + From 0e37bb3ab6b603fc58bd296c5f528915fa9c7ed4 Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Tue, 25 Oct 2022 16:59:32 -0500 Subject: [PATCH 08/10] Removed cake tooling --- ColorCode.sln | 1 - build/Build.bat | 3 - build/build.cake | 177 ----------------------- build/build.ps1 | 274 ------------------------------------ build/tools/packages.config | 4 - 5 files changed, 459 deletions(-) delete mode 100644 build/Build.bat delete mode 100644 build/build.cake delete mode 100644 build/build.ps1 delete mode 100644 build/tools/packages.config diff --git a/ColorCode.sln b/ColorCode.sln index 4365b2c..c8355f3 100644 --- a/ColorCode.sln +++ b/ColorCode.sln @@ -20,7 +20,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A4B1B99B-FC3A-4C76-8B46-B96723829FD2}" ProjectSection(SolutionItems) = preProject azure-pipelines.yml = azure-pipelines.yml - build\build.cake = build\build.cake ColorCode.snk = ColorCode.snk Directory.Build.props = Directory.Build.props Directory.Build.targets = Directory.Build.targets diff --git a/build/Build.bat b/build/Build.bat deleted file mode 100644 index f541994..0000000 --- a/build/Build.bat +++ /dev/null @@ -1,3 +0,0 @@ -@ECHO OFF -PowerShell.exe -file build.ps1 -PAUSE \ No newline at end of file diff --git a/build/build.cake b/build/build.cake deleted file mode 100644 index 2c085d7..0000000 --- a/build/build.cake +++ /dev/null @@ -1,177 +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.244 - -#tool nuget:?package=vswhere&version=2.8.4 - -using System; -using System.Linq; -using System.Text.RegularExpressions; - -////////////////////////////////////////////////////////////////////// -// ARGUMENTS -////////////////////////////////////////////////////////////////////// - -var target = Argument("target", "Default"); - -////////////////////////////////////////////////////////////////////// -// PREPARATION -////////////////////////////////////////////////////////////////////// - -var baseDir = MakeAbsolute(Directory("../")).ToString(); -var buildDir = baseDir + "/build"; - -var Solution = baseDir + "/ColorCode.sln"; -var nupkgDir = buildDir + "/nupkg"; - -string Version = null; - -////////////////////////////////////////////////////////////////////// -// METHODS -////////////////////////////////////////////////////////////////////// - -void VerifyHeaders(bool Replace) -{ - var header = FileReadText("header.txt") + "\r\n"; - bool hasMissing = false; - - Func 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("// ")) - { - 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."); - } -} - -void RetrieveVersion() -{ - Information("\nRetrieving version..."); - Version = GitVersioningGetVersion().NuGetPackageVersion; - Information("\nBuild Version: " + Version); -} - -void UpdateToolsPath(MSBuildSettings buildSettings) -{ - // Workaround for https://github.com/cake-build/cake/issues/2128 - var vsInstallation = VSWhereLatest(new VSWhereLatestSettings { Requires = "Microsoft.Component.MSBuild", IncludePrerelease = false }); - - if (vsInstallation != null) - { - buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\Current\Bin\MSBuild.exe"); - if (!FileExists(buildSettings.ToolPath)) - buildSettings.ToolPath = vsInstallation.CombineWithFilePath(@"MSBuild\15.0\Bin\MSBuild.exe"); - } -} - -////////////////////////////////////////////////////////////////////// -// TASKS -////////////////////////////////////////////////////////////////////// - -Task("Clean") - .Does(() => -{ - Information("\nCleaning Package Directory"); - CleanDirectory(nupkgDir); -}); - -Task("Restore-NuGet-Packages") - .IsDependentOn("Clean") - .Does(() => -{ - DotNetCoreRestore(Solution); -}); - -Task("Verify") - .Description("Run pre-build verifications") - .IsDependentOn("Clean") - .Does(() => -{ - VerifyHeaders(false); - - StartPowershellFile("./Find-WindowsSDKVersions.ps1"); -}); - -Task("Version") - .Description("Updates the version information in all Projects") - .IsDependentOn("Verify") - .IsDependentOn("Restore-NuGet-Packages") - .Does(() => -{ - RetrieveVersion(); -}); - -Task("Build") - .IsDependentOn("Version") - .Does(() => -{ - Information("\nBuilding Solution"); - var buildSettings = new MSBuildSettings - { - MaxCpuCount = 0 - } - .SetConfiguration("Release") - .WithTarget("Pack") - .WithProperty("GenerateLibraryLayout", "true") - .WithProperty("PackageOutputPath", nupkgDir); - - UpdateToolsPath(buildSettings); - - EnsureDirectoryExists(nupkgDir); - - MSBuild(Solution, buildSettings); -}); - -////////////////////////////////////////////////////////////////////// -// TASK TARGETS -////////////////////////////////////////////////////////////////////// - -Task("Default") - .IsDependentOn("Build"); - -Task("UpdateHeaders") - .Description("Updates the headers in *.cs files") - .Does(() => -{ - VerifyHeaders(true); -}); - -////////////////////////////////////////////////////////////////////// -// EXECUTION -////////////////////////////////////////////////////////////////////// - -RunTarget(target); diff --git a/build/build.ps1 b/build/build.ps1 deleted file mode 100644 index 2636495..0000000 --- a/build/build.ps1 +++ /dev/null @@ -1,274 +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 ($file -ne $null) - { - $file.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 ($NUGET_EXE_IN_PATH -ne $null -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 " ")" -exit $LASTEXITCODE \ No newline at end of file diff --git a/build/tools/packages.config b/build/tools/packages.config deleted file mode 100644 index 2a03746..0000000 --- a/build/tools/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - From 0db139e4e0aba7e5f4c3e7ae3b1e8254e2a2ca44 Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Wed, 26 Oct 2022 18:48:26 -0500 Subject: [PATCH 09/10] Use PackageOutputPath instead of copying files --- azure-pipelines.yml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 44d99ed..a55e363 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -47,15 +47,9 @@ steps: - powershell: .\build\Install-WindowsSdkISO.ps1 18362 -- script: msbuild -p:Configuration=Release -r -t:pack .\ColorCode.sln +- script: msbuild -p:Configuration=Release -r -t:pack -p:GenerateLibraryLayout=true -p:PackageOutputPath=..\build\nupkg .\ColorCode.sln displayName: Build and pack -- task: CopyFiles@2 - inputs: - Contents: '**\ColorCode.*.nupkg' - TargetFolder: 'build\nupkg' - flattenFolders: true - - task: PowerShell@2 displayName: Authenticode Sign Packages inputs: From 37c0244a88ab7e0ccfce55a412f2ef9c54d9241a Mon Sep 17 00:00:00 2001 From: Arlo Godfrey Date: Wed, 26 Oct 2022 19:01:10 -0500 Subject: [PATCH 10/10] Use .editorconfig for file headers --- .editorconfig | 15 +++++++++++++++ ColorCode.sln | 1 + build/UpdateHeaders.bat | 3 --- build/header.txt | 3 --- 4 files changed, 16 insertions(+), 6 deletions(-) create mode 100644 .editorconfig delete mode 100644 build/UpdateHeaders.bat delete mode 100644 build/header.txt diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7589c46 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# Generated code +[*{_AssemblyInfo.cs,.g.cs}] +generated_code = true + +# All files +[*] + +# .NET Foundation Header +file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license.\nSee the LICENSE file in the project root for more information. + +# Require file header +dotnet_diagnostic.IDE0073.severity = warning diff --git a/ColorCode.sln b/ColorCode.sln index c8355f3..b67cc75 100644 --- a/ColorCode.sln +++ b/ColorCode.sln @@ -19,6 +19,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ColorCode.WinUI", "ColorCod EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A4B1B99B-FC3A-4C76-8B46-B96723829FD2}" ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig azure-pipelines.yml = azure-pipelines.yml ColorCode.snk = ColorCode.snk Directory.Build.props = Directory.Build.props diff --git a/build/UpdateHeaders.bat b/build/UpdateHeaders.bat deleted file mode 100644 index 5587277..0000000 --- a/build/UpdateHeaders.bat +++ /dev/null @@ -1,3 +0,0 @@ -@ECHO OFF -PowerShell.exe -file "%~dp0build.ps1" -Target UpdateHeaders -PAUSE \ No newline at end of file diff --git a/build/header.txt b/build/header.txt deleted file mode 100644 index 45274ba..0000000 --- a/build/header.txt +++ /dev/null @@ -1,3 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information.