Skip to content

Commit 0822dd7

Browse files
baywetCopilotCopilot
authored
.NET: add public API analyzers (microsoft#7935)
* ci(dotnet): add public API analyzers Add PublicAPI analyzer coverage for released .NET packages, including nullable-aware shipped baselines and unshipped API publish validation. Add automation to promote unshipped API entries into shipped baselines after release branches move forward. Co-authored-by: Copilot <[email protected]> * ci: write all errors Co-authored-by: Copilot Autofix powered by AI <[email protected]> * ci: group subsequent pushes Co-authored-by: Copilot Autofix powered by AI <[email protected]> * ci: removes extraneous feature branch from promotion * ci: moves unshipped APIs to the correct file * ci: error if public api export is missing * ci: adds missing public api exports * ci: better information message Co-authored-by: Copilot Autofix powered by AI <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent 9ca9571 commit 0822dd7

88 files changed

Lines changed: 12888 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
name: Promote Shipped APIs
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
workflow_dispatch:
8+
9+
permissions:
10+
contents: write
11+
pull-requests: write
12+
13+
concurrency:
14+
group: ${{ github.workflow }}-${{ github.ref }}
15+
cancel-in-progress: false
16+
17+
jobs:
18+
promote-apis:
19+
runs-on: ubuntu-latest
20+
21+
steps:
22+
- name: Checkout code
23+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
24+
with:
25+
fetch-depth: 0
26+
token: ${{ secrets.GITHUB_TOKEN }}
27+
28+
- name: Configure git
29+
shell: pwsh
30+
run: |
31+
git config user.name "github-actions[bot]"
32+
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
33+
34+
- name: Check for existing PR
35+
id: check_pr
36+
shell: pwsh
37+
env:
38+
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
39+
run: |
40+
$branch = "${{ github.ref_name }}"
41+
$prBranch = "promote-shipped-apis-$branch"
42+
$prNumber = gh pr list --state open --head $prBranch --base $branch --json number --jq '.[0].number'
43+
44+
if ($prNumber) {
45+
"pr_exists=true" >> $env:GITHUB_OUTPUT
46+
"pr_number=$prNumber" >> $env:GITHUB_OUTPUT
47+
Write-Host "Found existing PR: $prNumber"
48+
} else {
49+
"pr_exists=false" >> $env:GITHUB_OUTPUT
50+
Write-Host "No existing PR found."
51+
}
52+
53+
- name: Checkout existing PR branch
54+
if: steps.check_pr.outputs.pr_exists == 'true'
55+
shell: pwsh
56+
run: |
57+
$branch = "${{ github.ref_name }}"
58+
$prBranch = "promote-shipped-apis-$branch"
59+
60+
git fetch origin $prBranch
61+
git checkout $prBranch
62+
git merge origin/$branch -m "Merge $branch into promote-shipped-apis branch"
63+
64+
- name: Run public API promotion script
65+
shell: pwsh
66+
run: ./dotnet/eng/scripts/promote-shipped-apis.ps1
67+
68+
- name: Check for changes
69+
id: check_changes
70+
shell: pwsh
71+
run: |
72+
$changes = git diff --name-only -- "dotnet/src/**/PublicAPI.*.txt"
73+
if ($changes) {
74+
"has_changes=true" >> $env:GITHUB_OUTPUT
75+
Write-Host "Changed files:"
76+
Write-Host $changes
77+
} else {
78+
"has_changes=false" >> $env:GITHUB_OUTPUT
79+
Write-Host "No public API promotion changes detected."
80+
}
81+
82+
- name: Commit and push changes
83+
if: steps.check_changes.outputs.has_changes == 'true'
84+
shell: pwsh
85+
run: |
86+
$branch = "${{ github.ref_name }}"
87+
$prBranch = "promote-shipped-apis-$branch"
88+
89+
git checkout -B $prBranch
90+
git add dotnet/src/**/PublicAPI.*.txt
91+
git commit -m "chore: promote shipped .NET APIs"
92+
git push --force-with-lease --set-upstream origin $prBranch
93+
94+
- name: Create new PR
95+
if: steps.check_pr.outputs.pr_exists == 'false' && steps.check_changes.outputs.has_changes == 'true'
96+
shell: pwsh
97+
env:
98+
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
99+
run: |
100+
$branch = "${{ github.ref_name }}"
101+
$prBranch = "promote-shipped-apis-$branch"
102+
$title = "chore: promote shipped .NET APIs for $branch"
103+
$body = "Automatically promotes entries from PublicAPI.Unshipped.txt to PublicAPI.Shipped.txt for released .NET packages."
104+
105+
gh pr create --title $title --base $branch --head $prBranch --body $body

‎CONTRIBUTING.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ individual projects may opt out (for example by setting `EnablePackageValidation
105105

106106
For more details, see the [Package Validation diagnostic IDs](https://learn.microsoft.com/dotnet/fundamentals/package-validation/diagnostic-ids).
107107

108+
#### Public API Baselines
109+
110+
Released .NET packages also use `Microsoft.CodeAnalysis.PublicApiAnalyzers` to make source-level public API changes visible during builds. The `PublicAPI.*.txt` files use `#nullable enable` so nullability annotations are tracked as part of the public API surface. When adding, changing, or removing public APIs in a released package, update the package's `PublicAPI.Unshipped.txt` file with the analyzer-provided entries and include that change in your PR. The build will fail if public API changes are not reflected in the baseline files.
111+
112+
After a release, the `Promote Shipped APIs` workflow moves entries from `PublicAPI.Unshipped.txt` to `PublicAPI.Shipped.txt` and opens or updates a promotion PR. Publish builds fail if released packages still contain unshipped public API entries.
113+
108114
### Suggested Workflow
109115

110116
We use and recommend the following workflow:

‎dotnet/Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@
160160
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
161161
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
162162
<PackageVersion Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.100" />
163+
<PackageVersion Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="5.6.0" />
163164
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers">
164165
<PrivateAssets>all</PrivateAssets>
165166
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
param(
2+
[string] $Path = (Join-Path $PSScriptRoot '..\..\src')
3+
)
4+
5+
$ErrorActionPreference = 'Stop'
6+
7+
$root = Resolve-Path $Path
8+
$encoding = [System.Text.UTF8Encoding]::new($true)
9+
$nullableHeader = '#nullable enable'
10+
$promotedFiles = 0
11+
$promotedApis = 0
12+
13+
Get-ChildItem -Path $root -Recurse -Filter 'PublicAPI.Unshipped.txt' | ForEach-Object {
14+
$unshippedFile = $_.FullName
15+
$shippedFile = Join-Path $_.DirectoryName 'PublicAPI.Shipped.txt'
16+
17+
$unshippedLines = if ((Get-Item $unshippedFile).Length -gt 0) {
18+
Get-Content -Path $unshippedFile -Encoding UTF8 | Where-Object {
19+
-not [string]::IsNullOrWhiteSpace($_) -and $_ -ne $nullableHeader
20+
}
21+
}
22+
else {
23+
@()
24+
}
25+
26+
if ($unshippedLines.Count -eq 0) {
27+
return
28+
}
29+
30+
$allLines = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::Ordinal)
31+
if (Test-Path $shippedFile) {
32+
Get-Content -Path $shippedFile -Encoding UTF8 | Where-Object {
33+
-not [string]::IsNullOrWhiteSpace($_) -and $_ -ne $nullableHeader
34+
} | ForEach-Object {
35+
$null = $allLines.Add($_)
36+
}
37+
}
38+
39+
$unshippedLines | ForEach-Object {
40+
$null = $allLines.Add($_)
41+
}
42+
43+
$shippedLines = @($nullableHeader) + @($allLines)
44+
$shippedContent = [string]::Join("`n", $shippedLines) + "`n"
45+
46+
[System.IO.File]::WriteAllText($shippedFile, $shippedContent, $encoding)
47+
[System.IO.File]::WriteAllText($unshippedFile, "$nullableHeader`n", $encoding)
48+
49+
$promotedFiles++
50+
$promotedApis += $unshippedLines.Count
51+
Write-Host "Promoted $($unshippedLines.Count) public API entries in $($_.Directory.Name)."
52+
}
53+
54+
Write-Host "Promoted $promotedApis public API baseline entries across $promotedFiles baseline file(s)."
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
param(
2+
[string] $Path = (Join-Path $PSScriptRoot '..\..\src')
3+
)
4+
5+
$ErrorActionPreference = 'Stop'
6+
7+
$root = Resolve-Path $Path
8+
$nullableHeader = '#nullable enable'
9+
$filesWithUnshippedApis = @()
10+
11+
Get-ChildItem -Path $root -Recurse -Filter 'PublicAPI.Unshipped.txt' | ForEach-Object {
12+
$entries = if ((Get-Item $_.FullName).Length -gt 0) {
13+
Get-Content -Path $_.FullName -Encoding UTF8 | Where-Object {
14+
-not [string]::IsNullOrWhiteSpace($_) -and $_ -ne $nullableHeader
15+
}
16+
}
17+
else {
18+
@()
19+
}
20+
21+
if ($entries.Count -gt 0) {
22+
$filesWithUnshippedApis += [PSCustomObject]@{
23+
Path = $_.FullName
24+
Count = $entries.Count
25+
}
26+
}
27+
}
28+
29+
if ($filesWithUnshippedApis.Count -eq 0) {
30+
Write-Host 'No unshipped public APIs found.'
31+
exit 0
32+
}
33+
34+
Write-Error 'Unshipped public APIs must be promoted before publishing released packages.' -ErrorAction Continue
35+
$filesWithUnshippedApis | ForEach-Object {
36+
Write-Error "$($_.Path): $($_.Count) unshipped public API entr$(if ($_.Count -eq 1) { 'y' } else { 'ies' })" -ErrorAction Continue
37+
}
38+
39+
exit 1

‎dotnet/nuget/nuget-package.props‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,25 @@
6464
<!-- SourceLink allows step-through debugging for source hosted on GitHub. -->
6565
<!-- https://github.com/dotnet/sourcelink -->
6666
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" />
67+
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" PrivateAssets="All" Condition="'$(IsReleased)' == 'true'">
68+
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
69+
</PackageReference>
70+
<AdditionalFiles Include="PublicAPI\$(TargetFramework)\PublicAPI.Shipped.txt" Condition="'$(IsReleased)' == 'true' AND '$(TargetFramework)' != ''" />
71+
<AdditionalFiles Include="PublicAPI\$(TargetFramework)\PublicAPI.Unshipped.txt" Condition="'$(IsReleased)' == 'true' AND '$(TargetFramework)' != ''" />
6772
</ItemGroup>
6873

74+
<Target Name="ValidatePublicApiBaselineFiles" BeforeTargets="CoreCompile" Condition="'$(IsReleased)' == 'true' AND '$(TargetFramework)' != ''">
75+
<ItemGroup>
76+
<_MissingPublicApiBaselineFile Include="PublicAPI\$(TargetFramework)\PublicAPI.Shipped.txt" Condition="!Exists('$(MSBuildProjectDirectory)\PublicAPI\$(TargetFramework)\PublicAPI.Shipped.txt')" />
77+
<_MissingPublicApiBaselineFile Include="PublicAPI\$(TargetFramework)\PublicAPI.Unshipped.txt" Condition="!Exists('$(MSBuildProjectDirectory)\PublicAPI\$(TargetFramework)\PublicAPI.Unshipped.txt')" />
78+
</ItemGroup>
79+
<Error Condition="'@(_MissingPublicApiBaselineFile)' != ''" Text="Released project '$(MSBuildProjectName)' targets '$(TargetFramework)' but is missing required public API baseline file(s): @(_MissingPublicApiBaselineFile, ', ')" />
80+
</Target>
81+
82+
<Target Name="ValidateNoUnshippedPublicApis" BeforeTargets="Pack" Condition="'$(IsReleased)' == 'true' AND '$(Configuration)' == 'Publish'">
83+
<Exec Command="pwsh &quot;$(RepoRoot)\dotnet\eng\scripts\test-unshipped-public-apis.ps1&quot; -Path &quot;$(MSBuildProjectDirectory)&quot;" />
84+
</Target>
85+
6986
<ItemGroup>
7087
<!-- Include icon.png and NUGET.md in the project. -->
7188
<None Include="$(RepoRoot)/dotnet/nuget/icon.png" Link="icon.png" Pack="true" PackagePath="." />

0 commit comments

Comments
 (0)