name: Publish to NuGet # 触发条件:当有标签被推送到仓库时触发该工作流(例如 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: Determine tag version id: tag_version run: | set -e # GITHUB_REF example: refs/tags/v0.0.1 or refs/tags/0.0.1 echo "GITHUB_REF = ${GITHUB_REF}" TAG=${GITHUB_REF#refs/tags/} # remove leading 'v' or 'V' if present VERSION=${TAG#v} VERSION=${VERSION#V} echo "tag='$TAG' -> version='$VERSION'" echo "version=$VERSION" >> $GITHUB_OUTPUT - name: Pack (use tag version) run: | set -e echo "Packing with version=${{ steps.tag_version.outputs.version }}" dotnet pack --no-build -c Release -o ./packages -p:PackageVersion=${{ steps.tag_version.outputs.version }} - name: Show packages run: ls -la ./packages || true - name: NuGet login (OIDC → temp API key) id: login uses: NuGet/login@v1 with: # 推荐把用户名放到仓库 Secret(不是邮箱),例如 ${{ secrets.NUGET_USER }} # 也可以直接写用户名(不推荐),但通常使用 secret 更安全 user: ${{ secrets.NUGET_USER }} - name: NuGet push (using short-lived API key) run: | set -e PKG=$(find ./packages -name "*.nupkg" | head -n1) if [ -z "$PKG" ]; then echo "No package found" exit 1 fi echo "Pushing $PKG to nuget.org..." # 注意:不要使用 --verbosity(dotnet nuget push 不支持) dotnet nuget push "$PKG" \ --api-key "${{ steps.login.outputs.NUGET_API_KEY }}" \ --source https://api.nuget.org/v3/index.json \ --skip-duplicate