name: Create Release (on tag) + Publish to NuGet (OIDC)
# 触发条件:当有标签被推送到仓库时触发该工作流(例如 v1.0.0 或 1.0.0)
on:
push:
tags:
- '*'
# 顶级权限:允许创建 Release(contents: write)和写 packages(如果需要)
permissions:
contents: write
packages: write
jobs:
build-and-publish:
runs-on: ubuntu-latest
# 允许此 job 请求短时 OIDC token(NuGet/login 使用)
permissions:
id-token: write
contents: write
packages: write
steps:
- name: Checkout repository (at tag)
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: true
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 9.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore -c Release
- name: Test
run: dotnet test --no-build -c Release --verbosity normal
- name: Pack
run: dotnet pack --no-build -c Release -o ./packages
- name: Show packages
run: ls -la ./packages || true
- name: Get Version and Package Path
id: get_version
run: |
set -e
PACKAGE_FILE=$(find ./packages -name "*.nupkg" | head -n 1)
if [ -z "$PACKAGE_FILE" ]; then
echo "No .nupkg file found in ./packages"
exit 1
fi
VERSION=$(unzip -p "$PACKAGE_FILE" *.nuspec 2>/dev/null | sed -n 's:.*\(.*\).*:\1:p' | head -n1)
if [ -z "$VERSION" ]; then
echo "Failed to parse version from $PACKAGE_FILE"
exit 1
fi
BASENAME=$(basename "$PACKAGE_FILE")
echo "package_file=$PACKAGE_FILE" >> $GITHUB_OUTPUT
echo "package_basename=$BASENAME" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
# -----------------------
# Get a short-lived NuGet API key via GitHub OIDC (NuGet login)
# -----------------------
- name: NuGet login (OIDC → temp API key)
id: login
uses: NuGet/login@v1
with:
# 推荐把用户名放到仓库 Secret(不是邮箱),例如 ${{ secrets.NUGET_USER }}
# 也可以直接写用户名(不推荐),但通常使用 secret 更安全
user: ${{ secrets.NUGET_USER }}
- name: Debug NuGet/login outputs (no secret printed)
run: |
echo "---- Debug: show package info and login output length ----"
ls -la ./packages || true
PKG=$(find ./packages -name "*.nupkg" | head -n1)
if [ -z "$PKG" ]; then
echo "No .nupkg found"
exit 1
fi
echo "Found package: $PKG"
echo "nuspec :"
unzip -p "$PKG" *.nuspec 2>/dev/null | sed -n 's:.*\(.*\).*:\1:p' || true
echo "nuspec :"
unzip -p "$PKG" *.nuspec 2>/dev/null | sed -n 's:.*\(.*\).*:\1:p' || true
# Check NuGet/login output length (do NOT print the key)
echo -n "Length of steps.login.outputs.NUGET_API_KEY: "
echo -n "${{ steps.login.outputs.NUGET_API_KEY }}" | wc -c
echo
# Also check whether the login step reported any error (GitHub Actions will show step logs)
echo "---- end debug ----"
- name: NuGet push (using short-lived API key from NuGet/login)
run: |
set -e
PKG="${{ steps.get_version.outputs.package_file }}"
if [ -z "$PKG" ]; then
echo "No package to push"
exit 1
fi
echo "Pushing $PKG to nuget.org (via OIDC short-lived key)..."
dotnet nuget push "$PKG" \
--api-key "${{ steps.login.outputs.NUGET_API_KEY }}" \
--source https://api.nuget.org/v3/index.json \
--skip-duplicate