Skip to content

About

Leosac Shared Github Actions

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Shared GitHub Actions

Reusable CI building blocks for Leosac repositories. No scripts need to be copied into consuming projects.

.NET library workflow

Create .github/workflows/build.yml in a consuming repository:

name: Build
on:
  push:
    branches: ['**']
    tags: ['**']
  pull_request:
permissions:
  contents: read
  actions: read
  packages: write
jobs:
  build:
    uses: leosac/github-actions/.github/workflows/dotnet-library.yml@main
    with:
      runner: windows-latest
      dotnet-version: '10.0.x'
      solution: WpfApp.sln
      test-settings: WpfApp.Tests/WpfApp.Tests.runsettings
      package-path: WpfApp/bin/Release/*.nupkg
Input Default Description
runner ubuntu-latest Build/test runner. Use windows-latest for WPF.
dotnet-version 10.0.x SDK version(s) accepted by setup-dotnet. Install all runtimes needed by multi-target tests.
solution Required Solution or project restored and built, relative to the repository root.
test-target solution input Optional solution or test project included in the build. Omit to run all test projects in the solution.
test-runner vstest Test invocation mode: vstest or mtp. Must match the caller's runner configuration.
test-settings Empty VSTest-only runsettings file controlling coverage formats and exclusions. Rejected in MTP mode.
package-path Required Artifact glob for .nupkg files generated by the Release build.
publish-packages true Publish to GitHub Packages only for tag push events and successful builds/tests.

Projects must generate packages during build (GeneratePackageOnBuild=true). The default vstest mode requires a VSTest-compatible test SDK and coverlet.collector. With no runsettings, Coverlet's default Cobertura format is collected; use runsettings to request OpenCover or exclude generated code. Once published and accessible on a configured feed, Leosac.Tests can provide shared project-level settings: reference it from each test project and omit test-settings so the workflow does not override them. No implicit coverage threshold is enforced.

For Microsoft.Testing.Platform, set test-runner: mtp, use .NET SDK 10 or later, and select Microsoft.Testing.Platform in the caller's global.json (test.runner). Every targeted test project must use MTP and reference coverlet.MTP (not coverlet.collector) and Microsoft.Testing.Extensions.TrxReport. The workflow uses --coverlet --coverlet-output-format cobertura --report-trx, retaining timestamped coverage reports for each run. Reference Leosac.Tests 0.2.0 or later for shared MTP coverage defaults, or provide a complete Coverlet testconfig.json in each test project for custom exclusions. Project configs replace rather than merge with package defaults; VSTest collector runsettings are not translated. Omit test-settings in this mode. Install all target runtimes through the multiline dotnet-version input, for example:

      dotnet-version: |
        8.0.x
        10.0.x
      test-runner: mtp

The workflow restores and builds in Release mode, archives NuGet packages, then runs tests with coverage. It writes a job summary and uploads TRX/Cobertura/OpenCover reports even after test failures. Test failures remain failures; missing or invalid TRX reports fail the summary step explicitly. VSTest generates TRX filenames automatically rather than using a shared fixed filename. Counts aggregate all test projects and frameworks. Artifact names are nuget-<runner>-attempt-<n> and test-and-coverage-<runner>-attempt-<n>. A build-provenance-attempt-<n> artifact records the caller workflow, tag/ref, commit and run attempt for later promotion. Use one invocation per workflow run to avoid artifact-name collisions.

Publication runs on Ubuntu, downloads the exact archived packages and uses the caller repository's GITHUB_TOKEN with packages: write. NUGET_AUTH_TOKEN is a custom environment variable populated from secrets.GITHUB_TOKEN and passed explicitly to dotnet nuget push --api-key; the variable name itself does not configure authentication. This token is for GitHub Packages, not nuget.org, which uses OIDC Trusted Publishing to obtain a temporary API key. No PAT or secrets: inherit is needed. The caller must grant the permissions shown above; publishing can also be disabled with publish-packages: false. Package versions come from the project, not the tag. Increment versions before releasing; duplicate versions fail publication. Set RepositoryUrl to the consuming repository to associate packages correctly. New packages are private by default and may require visibility/access configuration. Packages are retained independently of Actions artifact expiration, subject to storage limits and organization policies.

The checkout inside this reusable workflow retrieves the calling repository. The summary script comes from the independently reusable composite action, not from the caller's checkout.

Solutions with multiple libraries and test projects

Omit test-target to run dotnet test on the entire solution. All included test projects must use the selected runner; their TRX counts are aggregated in the summary, and each coverage report is retained separately. A failure in any test project fails the job and prevents publication. Raw coverage reports are not merged into a solution-wide coverage percentage.

For VSTest, use a common test-settings file whose assembly filters include all libraries you want to measure, or omit it for default collection. For MTP, use each project's Coverlet configuration. package-path accepts multiline artifact globs, for example:

      solution: Product.sln
      package-path: |
        src/Library.One/bin/Release/*.nupkg
        src/Library.Two/bin/Release/*.nupkg

All matching packages are archived and published on tags. To run just one test project, set test-target: tests/Library.One.Tests/Library.One.Tests.csproj.

Manual NuGet promotion

The reusable workflow .github/workflows/promote-nuget.yml prepares an existing successful tag build, without rebuilding its packages. A caller-owned, environment-protected publish job invokes the shared publish-nuget composite action for nuget.org publication and the GitHub Release. Normal tag builds still publish to GitHub Packages as before. Promotion adds advisory dependency security reports and blocking package integrity checks. Existing callers must migrate to the two-job example below: without prepare-only: true, preparation fails explicitly rather than silently skipping publication.

Create a separate caller workflow on the consuming repository's default branch:

name: Promote release
on:
  workflow_run:
    workflows: [Build]
    types: [completed]
  workflow_dispatch:
    inputs:
      build-run-id:
        description: Successful tag build run ID (manual fallback)
        required: true
        type: string
      tag:
        description: Existing tag to promote (manual fallback)
        required: true
        type: string
permissions:
  contents: write
  actions: read
  id-token: write
jobs:
  promote:
    if: >-
      github.event_name == 'workflow_dispatch' ||
      (github.event.workflow_run.conclusion == 'success' &&
       github.event.workflow_run.event == 'push' &&
       github.event.workflow_run.head_repository.full_name == github.repository)
    uses: leosac/github-actions/.github/workflows/promote-nuget.yml@main
    with:
      build-run-id: ${{ github.event.workflow_run.id && format('{0}', github.event.workflow_run.id) || inputs.build-run-id }}
      tag: ${{ inputs.tag || '' }}
      solution: Product.sln
      runner: ubuntu-latest
      environment: publish
      nuget-user: ${{ vars.NUGET_USER }}
      prepare-only: true
  publish:
    needs: promote
    if: needs.promote.result == 'success' && needs.promote.outputs.tag != ''
    runs-on: ubuntu-latest
    concurrency:
      group: promote-nuget-tag-${{ github.repository }}-${{ needs.promote.outputs.tag }}
      cancel-in-progress: false
    environment: publish
    permissions:
      contents: write
      actions: read
      id-token: write
    steps:
      - name: Publish verified NuGet release
        uses: leosac/github-actions/actions/publish-nuget@main
        with:
          build-run-id: ${{ github.event.workflow_run.id && format('{0}', github.event.workflow_run.id) || inputs.build-run-id }}
          build-attempt: ${{ needs.promote.outputs.attempt }}
          build-sha: ${{ needs.promote.outputs.sha }}
          tag: ${{ needs.promote.outputs.tag }}
          dotnet-version: '10.0.x'
          nuget-user: ${{ vars.NUGET_USER }}
          prerelease: 'false'

Configure the publish environment in the consuming repository before running this workflow:

  • Set the repository or organization Actions variable NUGET_USER to the nuget.org username of the person who created the Trusted Publishing policy (profile name, not email or necessarily the package/policy owner). If it is organization-scoped, allow the consuming repository access. Use an Actions variable rather than an environment-only variable because the preparation input is evaluated before the publishing environment is entered.
  • On nuget.org > Trusted Publishing, add a GitHub policy for the consuming repository's owner and name, the caller's workflow filename only (promote.yml in this example, not .github/workflows/promote.yml or the shared promote-nuget.yml), and environment publish. Select the appropriate package owner, package ID glob and publish scopes. For WpfApp: owner leosac, repository wpfapp, workflow promote.yml, environment publish. See NuGet Trusted Publishing. NuGet currently rejects OIDC login inside a reusable workflow from another repository because it validates job_workflow_ref; the caller-owned publish job and composite action are essential (NuGet/NuGetGallery#11000). Do not replace that job with a cross-repository reusable publishing workflow.
  • No long-lived API-key secret is required. The protected publishing job uses NuGet/login@v1.2.0 to exchange a GitHub OIDC token for a temporary API key immediately before pushing. The temporary key is valid for one hour; login or policy errors block publication without falling back to a stored key. The caller must grant id-token: write; only the reusable workflow's publishing job requests it. Remove any old NUGET_API_KEY secret and revoke the old API key after confirming a successful Trusted Publishing run.
  • Under Settings > Environments > publish > Required reviewers, select the release approver(s), and configure deployment branch restrictions for the default branch. The workflow_run path checks that a required-reviewer rule with at least one reviewer exists and fails explicitly if it is missing or cannot be read; it must not silently publish automatically. Merely naming an environment does not configure reviewers. GitHub plan/repository visibility may limit reviewer protection features; if unavailable, omit workflow_run and keep the explicit workflow_dispatch fallback. Protect the caller and shared workflow branches; review their changes as publishing code.
  • Package RepositoryUrl must identify the consuming repository. Versions must already be correct in the original build; the workflow neither rewrites versions nor rebuilds packages. All packages must be publishable to nuget.org under the configured Trusted Publishing policy. Private repositories may require a first successful publication within the policy's seven-day activation window; check its status on nuget.org.

After a successful tag Build, Promote release starts automatically using that exact build ID/attempt and derives the tag from its verified provenance. Ordinary branch builds skip the audit/publish jobs; failed, PR and fork builds are excluded. Once the audit/package checks finish, open the Promote release run, select Review deployments, select publish, then Approve and deploy. This is the manual promotion action: no build ID or tag is typed, and the original packages are not rebuilt. The build remains completed successfully while the separate promotion run waits. GitHub does not provide an arbitrary manual-job button in the completed build graph or matrix; environment approval is the native equivalent. The caller workflow must be on the default branch, and workflows: [Build] must match the source workflow's name, not its filename.

For an older eligible build or a prerelease, the fallback remains Actions > Promote release > Run workflow on the default branch: supply the source run ID/tag (and prerelease if exposed by the caller). Remove the workflow_run trigger for manual-only operation. Cancel an existing waiting promotion before launching an alternative for that build; preparation is serialized by build ID and publishing by verified tag. Package validation and all identity checks still apply. Automatic preparation uses prerelease: false; use the fallback if a GitHub prerelease is desired.

Preparation inputs: tag (inferred from provenance when omitted; checked for an exact match when supplied), build-workflow (default .github/workflows/build.yml), dotnet-version (10.0.x; install all target runtimes), runner (ubuntu-latest; use Windows for WPF), and environment (publish). build-run-id, solution, nuget-user and prepare-only: true are required for migrated callers. The workflow outputs verified tag, sha and attempt; the caller passes those to the publishing action only after successful preparation. Set prerelease on the action (GitHub Release status only; NuGet prerelease status comes from the package version). Source provenance artifacts must still be retained; this does not add an archive fallback.

The workflow verifies the source run's repository, workflow path, success, push event, commit, tag and run attempt. The build's provenance must confirm a tag push, not a branch push on the same commit. It also checks annotated tags and rechecks the tag/run immediately before release creation. No restriction is imposed on the tag commit's branch history. Builds created before provenance support, expired/missing artifacts and changed tags are rejected; make a fresh tag build with this shared workflow first. Do not rerun only a subset of source/promotion jobs: rerun the entire workflow so its attempt-specific artifacts stay together.

Dependency audits run without nuget.org credentials and use NuGet's vulnerability database to audit direct and transitive dependencies. All reported severities and audit errors (including restore/query failures or malformed reports) are advisory: they appear in a warning annotation, job summary and retained reports but do not fail promotion. An incomplete audit is reported as an error, never as a clean result. Package integrity and provenance checks remain blocking. Original .nupkg files are inspected without executing them, checking package identities, unique filenames and repository metadata, and recording SHA256 hashes. The credentialed Ubuntu job verifies these hashes before publishing. Reports (dependency-audit.json, restore log and package hash manifest) are retained as promotion artifacts and attached to the release. This is software-composition analysis, not a penetration test, malware scan or full OWASP assessment; no application is deployed or probed. Restore evaluates project build files, so only promote reviewed tags. The audit uses the dependency graph restored from the tagged source, not a reconstruction from each archived package's nuspec; floating dependencies can resolve differently from the original build. Pin dependency versions and commit lock files to improve reproducibility. Missing vulnerability entries are not proof that code is secure.

A draft GitHub Release is created with automatically generated release notes (customizable with the consuming repository's .github/release.yml), source build/promotion links and commit. Once nuget.org pushes succeed, the exact packages and nonempty security reports are attached and the release is published. Empty reports are retained in the promotion artifact but skipped with a notice because GitHub does not accept zero-byte release assets. There are no automatic duplicate-version skips: any push failure blocks completion. Multi-package publication is not transactional; a failure can leave some packages published and a draft release. Review that state and recover explicitly before retrying; an existing release for the tag intentionally blocks a blind rerun. In particular, an OIDC login failure occurs after draft creation: confirm that no package version was published and remove or resolve the draft manually before starting a new full promotion. If all packages were already pushed but release attachment failed, do not rerun the promotion or delete the draft: verify the published versions and package hashes against the retained checked packages and manifest, attach any missing nonempty package and report files from the promotion artifacts to the existing draft, then publish the draft manually. Review existing assets before attaching to avoid duplicates. Nuget.org publication cannot be rolled back by deleting the GitHub Release.

Only NuGet artifacts are supported initially. Missing packages fail explicitly; other artifact publishers can be added as separate reusable promotion workflows later. Once promoted, release assets remain independent of Actions artifact expiration, while pre-promotion builds must still have their retained Actions artifacts available. This workflow does not configure artifact retention or an archive fallback.

Test summary composite action

For projects that keep their own build/test steps:

- name: Test
  id: test
  run: dotnet test --logger trx --results-directory TestResults
- name: Summarize tests
  if: always() && steps.test.outcome != 'skipped'
  uses: leosac/github-actions/actions/test-summary@main
  with:
    results-directory: TestResults

results-directory defaults to TestResults and is searched recursively for TRX files. When MTP post-processing creates a merged subdirectory alongside original reports, the summary counts only the originals to avoid double-counting. If only merged reports are available, those are counted instead. PowerShell (pwsh) must be available on the runner; GitHub-hosted Windows and Ubuntu runners include it. The script uses the action's installation directory, so no additional checkout of this repository is required. Test names and messages are HTML-escaped. Missing files, malformed XML and invalid counters fail explicitly rather than reporting success.

Rollout and versioning

Push this repository's changes to main before merging consumers that reference them. If this repository is private, enable access for consuming repositories under Settings > Actions > General > Access; organization policy must also allow the referenced actions/workflows.

Initial consumers and the workflows' internal composite-action references use @main. For stable releases, first commit the composite actions, then pin their references inside dotnet-library.yml and promote-nuget.yml to that commit SHA (or action-specific release tags). Finally release/version the reusable workflows and update consumers to their SHAs or release tags. Pinning only an outer workflow while its internal action still uses @main does not freeze all behavior. Do not assume a v1 tag exists until it has been published.

Validate the scripts locally with PowerShell and Node.js (18 or later):

.\tests\test-summary.tests.ps1
.\tests\promotion-checks.tests.ps1
.\tests\promotion-advisory.tests.ps1
.\tests\trusted-publishing.tests.ps1
.\tests\test-runner.tests.ps1
node --test .\tests\promotion-trigger.tests.cjs

This repository's validation workflow runs those checks on Windows and Ubuntu. GitHub-hosted execution of the reusable workflow and publishing must be confirmed from a consuming repository after rollout.

About

Leosac Shared Github Actions

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages