CodeCheck.ps1 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #requires -version 5
  2. <#
  3. .SYNOPSIS
  4. This script runs a quick check for common errors, such as checking that Visual Studio solutions are up to date or that generated code has been committed to source.
  5. #>
  6. param(
  7. [switch]$ci,
  8. # Optional arguments that enable downloading an internal
  9. # runtime or runtime from a non-default location
  10. [Alias('DotNetRuntimeSourceFeed')]
  11. [string]$RuntimeSourceFeed,
  12. [Alias('DotNetRuntimeSourceFeedKey')]
  13. [string]$RuntimeSourceFeedKey
  14. )
  15. $ErrorActionPreference = 'Stop'
  16. Set-StrictMode -Version 1
  17. Import-Module -Scope Local -Force "$PSScriptRoot/common.psm1"
  18. $repoRoot = Resolve-Path "$PSScriptRoot/../.."
  19. [string[]] $errors = @()
  20. function LogError {
  21. param(
  22. [Parameter(Mandatory = $true, Position = 0)]
  23. [string]$message,
  24. [string]$FilePath,
  25. [string]$Code
  26. )
  27. if ($env:TF_BUILD) {
  28. $prefix = "##vso[task.logissue type=error"
  29. if ($FilePath) {
  30. $prefix = "${prefix};sourcepath=$FilePath"
  31. }
  32. if ($Code) {
  33. $prefix = "${prefix};code=$Code"
  34. }
  35. Write-Host "${prefix}]${message}"
  36. }
  37. $fullMessage = "error ${Code}: $message"
  38. if ($FilePath) {
  39. $fullMessage += " [$FilePath]"
  40. }
  41. Write-Host -f Red $fullMessage
  42. $script:errors += $fullMessage
  43. }
  44. try {
  45. if ($ci) {
  46. # Install dotnet.exe
  47. if ($RuntimeSourceFeed -or $RuntimeSourceFeedKey) {
  48. & $repoRoot/restore.cmd -ci -nobl -noBuildNodeJS -RuntimeSourceFeed $RuntimeSourceFeed `
  49. -RuntimeSourceFeedKey $RuntimeSourceFeedKey
  50. } else {
  51. & $repoRoot/restore.cmd -ci -nobl -noBuildNodeJS
  52. }
  53. }
  54. . "$repoRoot/activate.ps1"
  55. #
  56. # Duplicate .csproj files can cause issues with a shared build output folder
  57. #
  58. $projectFileNames = New-Object 'System.Collections.Generic.HashSet[string]'
  59. # Ignore duplicates in submodules. These should be isolated from the rest of the build.
  60. # Ignore duplicates in the .ref folder. This is expected.
  61. Get-ChildItem -Recurse "$repoRoot/src/*.*proj" |
  62. Where-Object { $_.FullName -notmatch 'submodules' -and $_.FullName -notmatch 'node_modules' } |
  63. Where-Object { (Split-Path -Leaf (Split-Path -Parent $_)) -ne 'ref' } |
  64. ForEach-Object {
  65. $fileName = [io.path]::GetFileNameWithoutExtension($_)
  66. if (-not ($projectFileNames.Add($fileName))) {
  67. LogError -code 'BUILD003' -filepath $_ `
  68. ("Multiple project files named '$fileName' exist. Project files should have a unique name " +
  69. "to avoid conflicts in build output.")
  70. }
  71. }
  72. #
  73. # Versions.props and Version.Details.xml
  74. #
  75. Write-Host "Checking that Versions.props and Version.Details.xml match"
  76. [xml] $versionProps = Get-Content "$repoRoot/eng/Versions.props"
  77. [xml] $versionDetails = Get-Content "$repoRoot/eng/Version.Details.xml"
  78. $globalJson = Get-Content $repoRoot/global.json | ConvertFrom-Json
  79. $versionVars = New-Object 'System.Collections.Generic.HashSet[string]'
  80. foreach ($vars in $versionProps.SelectNodes("//PropertyGroup[`@Label=`"Automated`"]/*")) {
  81. $versionVars.Add($vars.Name) | Out-Null
  82. }
  83. foreach ($dep in $versionDetails.SelectNodes('//Dependency')) {
  84. Write-Verbose "Found $dep"
  85. $expectedVersion = $dep.Version
  86. if ($dep.Name -in $globalJson.'msbuild-sdks'.PSObject.Properties.Name) {
  87. $actualVersion = $globalJson.'msbuild-sdks'.($dep.Name)
  88. if ($expectedVersion -ne $actualVersion) {
  89. LogError -filepath "$repoRoot\global.json" `
  90. ("MSBuild SDK version '$($dep.Name)' in global.json does not match the value in " +
  91. "Version.Details.xml. Expected '$expectedVersion', actual '$actualVersion'")
  92. }
  93. }
  94. else {
  95. $varName = $dep.Name -replace '\.',''
  96. $varName = $varName -replace '\-',''
  97. $varName = "${varName}Version"
  98. $versionVar = $versionProps.SelectSingleNode("//PropertyGroup[`@Label=`"Automated`"]/$varName")
  99. $actualVersion = $versionVar.InnerText
  100. $versionVars.Remove($varName) | Out-Null
  101. if (-not $versionVar) {
  102. LogError "Missing version variable '$varName' in the 'Automated' property group in $repoRoot/eng/Versions.props"
  103. continue
  104. }
  105. if ($expectedVersion -ne $actualVersion) {
  106. LogError -filepath "$repoRoot\eng\Versions.props" `
  107. ("Version variable '$varName' does not match the value in Version.Details.xml. " +
  108. "Expected '$expectedVersion', actual '$actualVersion'")
  109. }
  110. }
  111. }
  112. foreach ($unexpectedVar in $versionVars) {
  113. LogError -Filepath "$repoRoot\eng\Versions.props" `
  114. ("Version variable '$unexpectedVar' does not have a matching entry in Version.Details.xml. " +
  115. "See https://github.com/dotnet/aspnetcore/blob/main/docs/ReferenceResolution.md for instructions " +
  116. "on how to add a new dependency.")
  117. }
  118. # ComponentsWebAssembly-CSharp.sln is used by the templating engine; MessagePack.sln is irrelevant (in submodule).
  119. $solution = Get-ChildItem "$repoRoot/AspNetCore.sln"
  120. $solutionFile = Split-Path -Leaf $solution
  121. Write-Host "Checking that $solutionFile is up to date"
  122. # $solutionProjects will store relative paths i.e. the exact solution and solution filter content.
  123. $solutionProjects = New-Object 'System.Collections.Generic.HashSet[string]'
  124. # Where-Object needed to ignore heading `dotnet sln` outputs
  125. & dotnet sln $solution list | Where-Object { $_ -like '*proj' } | ForEach-Object {
  126. $proj = Join-Path $repoRoot $_
  127. if (-not ($solutionProjects.Add($_))) {
  128. LogError "Duplicate project. $solutionFile references a project more than once: $proj."
  129. }
  130. if (-not (Test-Path $proj)) {
  131. LogError "Missing project. $solutionFile references a project which does not exist: $proj."
  132. }
  133. }
  134. Write-Host "Checking solution filters"
  135. Get-ChildItem -Recurse "$repoRoot\*.slnf" | ForEach-Object {
  136. $solutionFilter = $_
  137. $json = Get-Content -Raw -Path $solutionFilter |ConvertFrom-Json
  138. $json.solution.projects | ForEach-Object {
  139. if (!$solutionProjects.Contains($_)) {
  140. LogError "$solutionFilter references a project not in $solutionFile`: $_"
  141. }
  142. }
  143. }
  144. #
  145. # Generated code check
  146. #
  147. Write-Host "Re-running code generation"
  148. Write-Host " Re-generating project lists"
  149. Invoke-Block {
  150. & $PSScriptRoot\GenerateProjectList.ps1 -ci:$ci
  151. }
  152. Write-Host " Re-generating package baselines"
  153. Invoke-Block {
  154. & dotnet run --project "$repoRoot/eng/tools/BaselineGenerator/"
  155. }
  156. Write-Host "Running git diff to check for pending changes"
  157. # Redirect stderr to stdout because PowerShell does not consistently handle output to stderr
  158. $changedFiles = & cmd /c 'git --no-pager diff --ignore-space-change --name-only 2>nul'
  159. # Temporary: Disable check for blazor js file and nuget.config (updated automatically for
  160. # internal builds)
  161. $changedFilesExclusions = @("src/Components/Web.JS/dist/Release/blazor.server.js", "NuGet.config")
  162. if ($changedFiles) {
  163. foreach ($file in $changedFiles) {
  164. if ($changedFilesExclusions -contains $file) {continue}
  165. $filePath = Resolve-Path "${repoRoot}/${file}"
  166. LogError -filepath $filePath `
  167. ("Generated code is not up to date in $file. You might need to regenerate the reference " +
  168. "assemblies or project list (see docs/ReferenceResolution.md)")
  169. & git --no-pager diff --ignore-space-change $filePath
  170. }
  171. }
  172. $targetBranch = $env:SYSTEM_PULLREQUEST_TARGETBRANCH
  173. if (![string]::IsNullOrEmpty($targetBranch)) {
  174. if ($targetBranch.StartsWith('refs/heads/')) {
  175. $targetBranch = $targetBranch.Replace('refs/heads/','')
  176. }
  177. # Retrieve the set of changed files compared to main
  178. Write-Host "Checking for changes to API baseline files $targetBranch"
  179. $changedFilesFromTarget = git --no-pager diff origin/$targetBranch --ignore-space-change --name-only --diff-filter=ar
  180. $changedAPIBaselines = [System.Collections.Generic.List[string]]::new()
  181. if ($changedFilesFromTarget) {
  182. foreach ($file in $changedFilesFromTarget) {
  183. # Check for changes in Shipped in all branches
  184. if ($file -like '*PublicAPI.Shipped.txt') {
  185. if (!$file.Contains('DevServer/src/PublicAPI.Shipped.txt')) {
  186. $changedAPIBaselines.Add($file)
  187. }
  188. }
  189. # Check for changes in Unshipped in servicing branches
  190. if ($targetBranch -like 'release*' -and $targetBranch -notlike '*preview*' -and $file -like '*PublicAPI.Unshipped.txt') {
  191. $changedAPIBaselines.Add($file)
  192. }
  193. }
  194. }
  195. Write-Host "Found changes in $($changedAPIBaselines.count) API baseline files"
  196. if ($changedAPIBaselines.count -gt 0) {
  197. LogError ("Detected modification to baseline API files. PublicAPI.Shipped.txt files should only " +
  198. "be updated after a major release. See /docs/APIBaselines.md for more information.")
  199. LogError "Modified API baseline files:"
  200. foreach ($file in $changedAPIBaselines) {
  201. LogError $file
  202. }
  203. }
  204. }
  205. }
  206. finally {
  207. Write-Host ""
  208. Write-Host "Summary:"
  209. Write-Host ""
  210. Write-Host " $($errors.Length) error(s)"
  211. Write-Host ""
  212. foreach ($err in $errors) {
  213. Write-Host -f Red $err
  214. }
  215. if ($errors) {
  216. exit 1
  217. }
  218. }