-
Notifications
You must be signed in to change notification settings - Fork 57
749 lines (650 loc) Β· 32.6 KB
/
build_windows_macos.yml
File metadata and controls
749 lines (650 loc) Β· 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
name: Build Windows and macOS Installers
on:
release:
types: [published]
workflow_dispatch:
push:
paths:
- '**/*.py' # Watch for changes in any Python files
concurrency:
group: ci-${{github.workflow}}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
build:
runs-on: 'windows-latest'
strategy:
matrix:
python-version: ['3.14']
outputs:
hashes: ${{ steps.hash.outputs.hashes }}
permissions:
contents: write
id-token: write
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@fa2e9d605c4eeb9fcad4c99c224cee0c6c7f3594 # v2.16.0
with:
egress-policy: audit
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# https://docs.astral.sh/uv/guides/integration/github/
- name: Install uv and set the python version
uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
with:
python-version: ${{ matrix.python-version }}
activate-environment: true
- name: Install dependencies
run: |
uv pip install .[win_dist]
- name: Restore Inno Setup installer from cache
id: cache-innosetup
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
with:
path: installer.exe
key: innosetup-6.5.4-exe
- name: Download Inno Setup installer
if: steps.cache-innosetup.outputs.cache-hit != 'true'
run: curl -L -o installer.exe https://files.jrsoftware.org/is/6/innosetup-6.5.4.exe
- name: Install Inno Setup
run: |
Start-Process -FilePath ./installer.exe -ArgumentList '/VERYSILENT','/ALLUSERS','/DIR=inst' -Wait -NoNewWindow
- name: Validate Inno Setup installation
run: |
if (-not (Test-Path "$env:GITHUB_WORKSPACE\inst\ISCC.exe")) {
Get-ChildItem inst -Recurse -ErrorAction SilentlyContinue | Format-List FullName, Length
throw 'Inno Setup compiler not found at inst\\ISCC.exe. Ensure the installer step completed successfully.'
}
- name: List installed software versions
run: |
python -m pip list
- name: Prepare installer
run: |
cd ardupilot_methodic_configurator
copy ..\\windows\\ardupilot_methodic_configurator.spec
pyinstaller --clean ardupilot_methodic_configurator.spec
del ardupilot_methodic_configurator.spec
- name: Write the git commit hash to file
run: |
$hash = git rev-parse HEAD
$hash = $hash.Trim()
$utf8NoBom = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText("git_hash.txt", $hash, $utf8NoBom)
- name: Verify git hash file
run: |
Write-Host "Git hash file content:"
$bytes = [System.IO.File]::ReadAllBytes("git_hash.txt")
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
Write-Host "::warning::File contains UTF-8 BOM"
} else {
Write-Host "File has no BOM (good)"
}
Get-Content -Raw git_hash.txt
- name: Debug GitHub token and permissions
run: |
Write-Host "Checking GitHub token and permissions"
# Don't print the actual token, just check if it exists
if ([string]::IsNullOrEmpty("${{ secrets.GITHUB_TOKEN }}")) {
Write-Host "::warning::GITHUB_TOKEN is empty or not accessible"
} else {
Write-Host "GITHUB_TOKEN is available"
}
# Check if running in fork (which may have limited permissions)
if ("${{ github.repository }}" -ne "${{ github.repository_owner }}/${{ github.event.repository.name }}") {
Write-Host "::warning::Running in a fork which may have limited permissions"
}
- name: Restore ChineseSimplified.isl from cache
id: cache-chinese-isl
uses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4
with:
path: ChineseSimplified.isl
key: chinese-simplified-isl-6.5
- name: Download ChineseSimplified.isl
if: steps.cache-chinese-isl.outputs.cache-hit != 'true'
run: |
curl -L -o ChineseSimplified.isl https://raw.githubusercontent.com/jrsoftware/issrc/refs/heads/main/Files/Languages/Unofficial/ChineseSimplified.isl
- name: Build installer
run: |
New-Item -ItemType Directory -Force -Path "inst\Languages"
Copy-Item "ChineseSimplified.isl" -Destination "inst\Languages\ChineseSimplified.isl"
cd windows
$env:VERSION=$(python return_version.py)
Start-Process -FilePath "..\inst\ISCC.exe" -ArgumentList "/dMyAppVersion=$env:VERSION", "ardupilot_methodic_configurator.iss" -Wait -NoNewWindow
Get-ChildItem Output
# https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/generic/README.md
- name: Generate hashes
id: hash
shell: bash
run: |
cd windows/Output
# Generate SHA256 hashes in the format expected by SLSA (sha256sum format)
sha256sum *.exe > checksums.txt
echo "hashes=$(cat checksums.txt | base64 -w0)" >> "$GITHUB_OUTPUT"
- name: Upload build artifacts
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: windows-installer
path: windows/Output/*.exe
retention-days: 7
build_macos:
runs-on: 'macos-latest'
strategy:
matrix:
python-version: ['3.14']
permissions:
contents: write
id-token: write
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@fa2e9d605c4eeb9fcad4c99c224cee0c6c7f3594 # v2.16.0
with:
egress-policy: audit
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up Python
id: setup-python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install .[mac_dist]
- name: Verify tkinter is available
run: |
python - <<'PY'
import tkinter
print(f"tkinter OK, TkVersion={tkinter.TkVersion}")
PY
- name: Write the git commit hash to file
run: |
git rev-parse HEAD | tr -d '\n' > git_hash.txt
- name: Prepare macOS icon
run: |
set -euo pipefail
ICON_SRC="ardupilot_methodic_configurator/images/ArduPilot_icon.png"
ICON_SET="macos/ArduPilotMethodicConfigurator.iconset"
ICON_OUT="macos/ArduPilotMethodicConfigurator.icns"
rm -rf "$ICON_SET" "$ICON_OUT"
mkdir -p "$ICON_SET"
sips -z 16 16 "$ICON_SRC" --out "$ICON_SET/icon_16x16.png"
sips -z 32 32 "$ICON_SRC" --out "$ICON_SET/icon_16x16@2x.png"
sips -z 32 32 "$ICON_SRC" --out "$ICON_SET/icon_32x32.png"
sips -z 64 64 "$ICON_SRC" --out "$ICON_SET/icon_32x32@2x.png"
sips -z 128 128 "$ICON_SRC" --out "$ICON_SET/icon_128x128.png"
sips -z 256 256 "$ICON_SRC" --out "$ICON_SET/icon_128x128@2x.png"
sips -z 256 256 "$ICON_SRC" --out "$ICON_SET/icon_256x256.png"
sips -z 512 512 "$ICON_SRC" --out "$ICON_SET/icon_256x256@2x.png"
sips -z 512 512 "$ICON_SRC" --out "$ICON_SET/icon_512x512.png"
sips -z 1024 1024 "$ICON_SRC" --out "$ICON_SET/icon_512x512@2x.png"
iconutil -c icns "$ICON_SET" -o "$ICON_OUT"
- name: Build macOS app with PyInstaller
run: |
pyinstaller --clean macos/ardupilot_methodic_configurator.spec
- name: Build DMG
run: |
set -euo pipefail
VERSION=$(cd windows && python return_version.py)
APP_NAME="ArduPilot Methodic Configurator.app"
DMG_NAME="ardupilot_methodic_configurator_${VERSION}_macos_setup.dmg"
STAGING_DIR="macos/dmg-staging"
OUTPUT_DIR="macos/Output"
rm -rf "$STAGING_DIR"
mkdir -p "$STAGING_DIR" "$OUTPUT_DIR"
cp -R "dist/${APP_NAME}" "$STAGING_DIR/"
ln -s /Applications "$STAGING_DIR/Applications"
hdiutil create -volname "ArduPilot Methodic Configurator" \
-srcfolder "$STAGING_DIR" \
-ov -format UDZO \
-fs HFS+ \
-imagekey zlib-level=9 \
"$OUTPUT_DIR/$DMG_NAME"
- name: Upload build artifacts
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: macos-dmg
path: macos/Output/*.dmg
retention-days: 7
# Generate SLSA provenance using the official generic workflow
# provenance:
# needs: [build]
# permissions:
# actions: read # To read the workflow path
# id-token: write # To sign the provenance
# contents: write # To add assets to a release
# uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@4876e96b8268fd8b7b8d8574718d06c0d0426d40 # latest commit
# with:
# base64-subjects: "${{ needs.build.outputs.hashes }}"
# upload-assets: ${{ startsWith(github.ref, 'refs/tags/v') }} # Only upload to releases for v* tags
# continue-on-error: false # Explicit error handling - fail fast for security issues
# Release job that depends on provenance generation
release:
# needs: [build, provenance]
needs: [build, build_macos]
runs-on: windows-latest
if: startsWith(github.ref, 'refs/tags/v') || github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
permissions:
contents: write
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@fa2e9d605c4eeb9fcad4c99c224cee0c6c7f3594 # v2.16.0
with:
egress-policy: audit
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Download build artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: windows-installer
path: release-artifacts
- name: Download macOS build artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: macos-dmg
path: release-artifacts
- name: Rename installer for pre-release
if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
shell: pwsh
run: |
$files = Get-ChildItem release-artifacts\*.* | Where-Object { $_.Extension -in '.exe', '.dmg' }
foreach ($file in $files) {
if ($file.Extension -eq '.exe') {
$newName = $file.Name -replace 'ardupilot_methodic_configurator_.*_windows_setup\.exe$', 'ardupilot_methodic_configurator_latest_pre_release_windows_setup.exe'
} elseif ($file.Extension -eq '.dmg') {
$newName = $file.Name -replace 'ardupilot_methodic_configurator_.*_macos_setup\.dmg$', 'ardupilot_methodic_configurator_latest_pre_release_macos_setup.dmg'
} else {
continue
}
if ($newName -ne $file.Name) {
Rename-Item $file.FullName $newName
Write-Host "Renamed $($file.Name) to $newName"
} else {
Write-Host "Skipped rename for $($file.Name) (pattern did not match)"
}
}
- name: Generate categorized release notes
id: release_notes
shell: pwsh
run: |
# Determine if this is a pre-release or stable release
$isPreRelease = "${{ github.ref }}" -eq "refs/heads/${{ github.event.repository.default_branch }}"
$isStableRelease = "${{ github.ref }}" -like "refs/tags/v*"
try {
if ($isPreRelease) {
# For pre-releases, compare against latest stable release
Write-Host "Fetching latest stable release..."
Write-Host "GitHub token available: $($env:GH_TOKEN -ne $null -and $env:GH_TOKEN -ne '')"
Write-Host "Repository: ${{ github.repository }}"
# Try multiple approaches to fetch releases
$releases = $null
# First try with gh CLI
try {
$releases = gh release list --repo "${{ github.repository }}" --limit 50 --json tagName,isPrerelease 2>$null
if ($LASTEXITCODE -ne 0) {
# Capture stderr for logging
$ghError = gh release list --repo "${{ github.repository }}" --limit 50 --json tagName,isPrerelease 1>$null 2>&1
Write-Host "gh CLI failed with exit code: $LASTEXITCODE"
Write-Host "gh CLI stderr: $ghError"
$releases = $null
}
}
catch {
Write-Host "gh CLI exception: $($_.Exception.Message)"
$releases = $null
}
# Fallback to REST API if gh CLI fails
if (-not $releases) {
Write-Host "Trying REST API fallback..."
try {
$releases = gh api "repos/${{ github.repository }}/releases?per_page=50" --jq '[.[] | {tagName: .tag_name, isPrerelease: .prerelease}]' | ConvertFrom-Json
}
catch {
Write-Host "REST API also failed: $($_.Exception.Message)"
}
}
if (-not $releases) {
Write-Host "All methods failed to fetch releases, using fallback"
$fallbackNotes = @"
**β οΈ This is an unstable development build. Use at your own risk!**
### Recent Changes:
Unable to fetch detailed change log. This build contains the latest development changes.
---
**Build Info:**
- Commit: [${{ github.sha }}](https://github.com/${{ github.repository }}/commit/${{ github.sha }})
- Build: #${{ github.run_number }}
- Date: $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')) UTC
**Full Changelog**: https://github.com/${{ github.repository }}/commits/${{ github.event.repository.default_branch }}
"@
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
$fallbackNotes | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
$releaseList = $releases | ConvertFrom-Json
$latestStable = $releaseList | Where-Object { $_.tagName -like "v*" } | Select-Object -First 1
if ($latestStable -and $latestStable.tagName) {
$compareFrom = $latestStable.tagName
$releaseType = "pre-release"
$releaseWarning = "**β οΈ This is an unstable development build. Use at your own risk!**"
Write-Host "Pre-release: Comparing against latest stable release: $compareFrom"
} else {
$compareFrom = ""
Write-Host "No stable release found for comparison"
}
} elseif ($isStableRelease) {
# For stable releases, compare against previous stable release
Write-Host "Fetching previous releases..."
Write-Host "Repository: ${{ github.repository }}"
# Try multiple approaches to fetch releases
$releases = $null
# First try with gh CLI
try {
$releases = gh release list --repo "${{ github.repository }}" --limit 50 --json tagName 2>$null
if ($LASTEXITCODE -ne 0) {
$errorOutput = gh release list --repo "${{ github.repository }}" --limit 50 --json tagName 2>&1
Write-Host "gh CLI failed with exit code: $LASTEXITCODE"
Write-Host "gh CLI error output: $errorOutput"
$releases = $null
}
}
catch {
Write-Host "gh CLI exception: $($_.Exception.Message)"
$releases = $null
}
# Fallback to REST API if gh CLI fails
if (-not $releases) {
Write-Host "Trying REST API fallback..."
try {
$releases = gh api "repos/${{ github.repository }}/releases?per_page=50" --jq '[.[] | {tagName: .tag_name}]' | ConvertFrom-Json
}
catch {
Write-Host "REST API also failed: $($_.Exception.Message)"
}
}
if (-not $releases) {
Write-Host "All methods failed to fetch releases, using fallback"
$currentVersion = "${{ github.ref }}" -replace "refs/tags/", ""
$fallbackNotes = @"
## π Stable Release
### Release ${currentVersion}:
Unable to fetch detailed change log. Please refer to the commit history for changes.
---
**Release Info:**
- Version: ${currentVersion}
- Date: $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')) UTC
**Full Changelog**: https://github.com/${{ github.repository }}/commits/${currentVersion}
"@
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
$fallbackNotes | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
$allReleases = $releases | ConvertFrom-Json
$currentTag = "${{ github.ref }}" -replace "refs/tags/", ""
$previousRelease = $allReleases | Where-Object { $_.tagName -ne $currentTag -and $_.tagName -like "v*" } | Select-Object -First 1
if ($previousRelease -and $previousRelease.tagName) {
$compareFrom = $previousRelease.tagName
$releaseType = "stable"
$releaseWarning = ""
Write-Host "Stable release: Comparing against previous release: $compareFrom"
} else {
$compareFrom = ""
Write-Host "No previous release found for comparison"
}
} else {
Write-Host "Neither pre-release nor stable release, skipping"
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
}
catch {
Write-Host "Error during release detection: $($_.Exception.Message). Using auto-generated notes."
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
if ($compareFrom) {
try {
# Get commits since comparison point with error handling
Write-Host "Fetching commits from $compareFrom to ${{ github.sha }}"
$commits = gh api "repos/${{ github.repository }}/compare/$compareFrom...${{ github.sha }}" --jq '.commits[] | {message: .commit.message, sha: .sha, author: .commit.author.name, login: (.author.login // ""), url: .html_url}' 2>$null
if (-not $commits) {
Write-Host "No commits found or API call failed, falling back to auto-generated notes"
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
$commitList = $commits | ConvertFrom-Json
if (-not $commitList -or $commitList.Count -eq 0) {
Write-Host "No commits to process"
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
}
catch {
Write-Host "Error fetching commits: $($_.Exception.Message). Using auto-generated notes."
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
return
}
# Initialize grouped commits using ArrayList for better performance
$contributors = @{}
$grouped = @{
'feat' = New-Object System.Collections.ArrayList
'fix' = New-Object System.Collections.ArrayList
'docs' = New-Object System.Collections.ArrayList
'style' = New-Object System.Collections.ArrayList
'refactor' = New-Object System.Collections.ArrayList
'perf' = New-Object System.Collections.ArrayList
'test' = New-Object System.Collections.ArrayList
'build' = New-Object System.Collections.ArrayList
'ci' = New-Object System.Collections.ArrayList
'chore' = New-Object System.Collections.ArrayList
'revert' = New-Object System.Collections.ArrayList
'other' = New-Object System.Collections.ArrayList
}
foreach ($commit in $commitList) {
# Input validation
if (-not $commit.message -or -not $commit.sha -or -not $commit.url) {
Write-Host "Skipping invalid commit object"
continue
}
$message = ($commit.message -split "`n" | Select-Object -First 1).Trim()
# Safe substring operation
$shortSha = if ($commit.sha.Length -ge 7) {
$commit.sha.Substring(0, 7)
} else {
$commit.sha
}
$commitUrl = $commit.url
# Track contributor
if ($commit.login -and $commit.login -ne "") {
$contributors[$commit.login] = $true
}
# Build author suffix
$authorSuffix = if ($commit.login -and $commit.login -ne "") {
" by [@$($commit.login)](https://github.com/$($commit.login))"
} else {
$rawAuthor = if ($commit.author) { [string]$commit.author } else { "Unknown author" }
$sanitizedAuthor = $rawAuthor -replace '[<>&"`\[\]\(\)@*_#|]', ''
" by $sanitizedAuthor"
}
# Sanitize message to prevent markdown injection
$sanitizedMessage = $message -replace '[<>&"]', '' -replace '\[', '\\[' -replace '\]', '\\]' -replace '`', '\\`'
# Parse conventional commit format
if ($sanitizedMessage -match '^(\w+)(\(.+\))?\s*!?\s*:\s*(.+)$') {
$type = $matches[1].ToLower()
$scope = if ($matches[2]) { ($matches[2] -replace '[()]', '') + ": " } else { "" }
$description = $matches[3].Trim()
# Limit description length (accounting for scope)
$maxLength = 100 - $scope.Length
if ($description.Length -gt $maxLength) {
if ($maxLength - 3 -gt 0) {
$description = $description.Substring(0, $maxLength - 3) + "..."
} else {
$description = "..."
}
}
$formattedDescription = $scope + $description
if ($grouped.ContainsKey($type)) {
$null = $grouped[$type].Add("- $formattedDescription ([$shortSha]($commitUrl))$authorSuffix")
} else {
$null = $grouped['other'].Add("- $formattedDescription ([$shortSha]($commitUrl))$authorSuffix")
}
} else {
# Non-conventional commit
$truncatedMessage = if ($sanitizedMessage.Length -gt 100) {
$sanitizedMessage.Substring(0, 97) + "..."
} else {
$sanitizedMessage
}
$null = $grouped['other'].Add("- $truncatedMessage ([$shortSha]($commitUrl))$authorSuffix")
}
}
# Build categorized release notes
$sections = @()
# Define section mappings with emojis
$sectionMap = @{
'feat' = @{ title = 'π New Features'; items = $grouped['feat'] }
'fix' = @{ title = 'π Bug Fixes'; items = $grouped['fix'] }
'docs' = @{ title = 'π Documentation'; items = $grouped['docs'] }
'perf' = @{ title = 'β‘ Performance'; items = $grouped['perf'] }
'refactor' = @{ title = 'β»οΈ Code Refactoring'; items = $grouped['refactor'] }
'style' = @{ title = 'π Style Changes'; items = $grouped['style'] }
'test' = @{ title = 'π§ͺ Tests'; items = $grouped['test'] }
'build' = @{ title = 'π¦ Build System'; items = $grouped['build'] }
'ci' = @{ title = 'βοΈ CI/CD'; items = $grouped['ci'] }
'chore' = @{ title = 'π§ Maintenance'; items = $grouped['chore'] }
'revert' = @{ title = 'βͺ Reverts'; items = $grouped['revert'] }
'other' = @{ title = 'π Other Changes'; items = $grouped['other'] }
}
# Process sections in a defined order for consistency
$orderedKeys = @('feat', 'fix', 'perf', 'refactor', 'docs', 'style', 'test', 'build', 'ci', 'chore', 'revert', 'other')
foreach ($key in $orderedKeys) {
if ($sectionMap.ContainsKey($key) -and $sectionMap[$key].items.Count -gt 0) {
$sections += ""
$sections += "### $($sectionMap[$key].title)"
$sections += ""
$sections += $sectionMap[$key].items.ToArray()
}
}
$changesSummary = if ($sections.Count -gt 0) { $sections -join "`n" } else { "No changes found." }
# Build contributors section
$contributorsSection = ""
if ($contributors.Count -gt 0) {
$contributorLinks = ($contributors.Keys | Sort-Object | ForEach-Object {
$username = $_
$escapedDisplayName = $username -replace '\[', '\\[' -replace '\]', '\\]'
$encodedUsername = [uri]::EscapeDataString($username)
"[@$escapedDisplayName](https://github.com/$encodedUsername)"
}) -join ', '
$contributorsSection = "`n`n### π₯ Contributors`n`n$contributorLinks"
}
# Build release notes based on release type
if ($isPreRelease) {
$fullNotes = @"
${releaseWarning}
### Changes since last stable release (${compareFrom}):
${changesSummary}${contributorsSection}
---
**Build Info:**
- Commit: [${{ github.sha }}](https://github.com/${{ github.repository }}/commit/${{ github.sha }})
- Build: #${{ github.run_number }}
- Date: $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')) UTC
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${compareFrom}...${{ github.sha }}
"@
} else {
$currentVersion = "${{ github.ref }}" -replace "refs/tags/", ""
$fullNotes = @"
### Changes since previous release (${compareFrom}):
${changesSummary}${contributorsSection}
---
**Release Info:**
- Version: ${currentVersion}
- Date: $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm:ss')) UTC
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${compareFrom}...${currentVersion}
"@
}
# Output the notes for next step (properly handle multiline)
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
$fullNotes | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
} else {
Write-Host "No comparison point found, using auto-generated notes"
"notes<<EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
"EOF" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Check for stable tags on current commit
id: check_tags
shell: pwsh
run: |
try {
$tags = gh api "repos/${{ github.repository }}/tags" --jq '[.[] | select(.name | startswith("v")) | select(.commit.sha == "${{ github.sha }}") | .name]'
$tagList = $tags | ConvertFrom-Json
if ($tagList -and $tagList.Count -gt 0) {
Write-Host "Found stable tags: $($tagList -join ', ')"
"has_stable_tag=true" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
} else {
Write-Host "No stable tags found on this commit"
"has_stable_tag=false" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
}
} catch {
Write-Host "Error checking tags: $($_.Exception.Message)"
"has_stable_tag=false" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Debug Pre Release Condition
shell: pwsh
run: |
$formatted = "refs/heads/${{ github.event.repository.default_branch }}"
Write-Host "github.ref == format('refs/heads/{{0}}', github.event.repository.default_branch):"
if ("${{ github.ref }}" -eq $formatted) { Write-Host 'true' } else { Write-Host 'false' }
Write-Host "steps.check_tags.outputs.has_stable_tag == 'false':"
if ("${{ steps.check_tags.outputs.has_stable_tag }}" -eq 'false') { Write-Host 'true' } else { Write-Host 'false' }
Write-Host "github.ref == 'refs/heads/master' && steps.check_tags.outputs.has_stable_tag == 'false':"
if (("${{ github.ref }}" -eq $formatted) -and ("${{ steps.check_tags.outputs.has_stable_tag }}" -eq 'false')) { Write-Host 'true' } else { Write-Host 'false' }
- name: Delete previous Pre Release
if: startsWith(github.ref, 'refs/tags/v') || (github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && steps.check_tags.outputs.has_stable_tag == 'false')
run: |
gh release delete latest-development-build --cleanup-tag
if ($LASTEXITCODE -eq 0) {
Write-Host "Successfully deleted previous release"
} else {
Write-Host "Release not found or failed to delete, continuing..."
}
$LASTEXITCODE = 0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Pre Release
uses: softprops/action-gh-release@153bb8e04406b158c6c84fc1615b65b24149a1fe # v2.6.1
if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && steps.check_tags.outputs.has_stable_tag == 'false'
with:
tag_name: "latest-development-build"
prerelease: true
name: "π§ Development Build π§"
files: release-artifacts/*
body: ${{ steps.release_notes.outputs.notes || '' }}
generate_release_notes: ${{ steps.release_notes.outputs.notes == '' }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Release
uses: softprops/action-gh-release@153bb8e04406b158c6c84fc1615b65b24149a1fe # v2.6.1
if: startsWith(github.ref, 'refs/tags/v')
with:
prerelease: false
files: release-artifacts/*
body: ${{ steps.release_notes.outputs.notes || '' }}
generate_release_notes: ${{ steps.release_notes.outputs.notes == '' }}
token: ${{ secrets.GITHUB_TOKEN }}
make_latest: true