GitHub Actions steps, written in C#.
The whole Actions toolkit, typed, in a run block. No project, no JavaScript, no bash.
name: Helloon: pushjobs: hello: runs-on: ubuntu-latest steps: - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - shell: dotnet run --file {0} run: | #:sdk ActionsToolkit.Sdk@11.0.0 var actor = GitHubApi.Context.Actor; Core.Info($"Hello from C#, {actor}!");#:sdk ActionsToolkit.Sdk brings in
CoreActionsToolkit.Core
Inputs, outputs, log groups, annotations, and the job summary.
var name = Core.GetInput("name", required: true);Core.Info($"Hello, {name}!");
ExecActionsToolkit.Exec
Run any command, stream it into the log, or capture its output.
var exitCode = await Exec.RunAsync( "dotnet", ["test", "--configuration", "Release"]);
IOActionsToolkit.IO
Copy, move, and remove files, and find tools on the PATH.
IO.MakeDirectory("publish");IO.Copy("README.md", "publish/README.md");
GlobActionsToolkit.Glob
Match files with glob patterns, including ** and exclusions.
var reports = Glob.Create("**/*.trx") .GlobFiles() .ToList();
HttpActionsToolkit.HttpClient
An HTTP client with basic, bearer, and token auth ready to go.
using var http = Http.CreateBearerTokenClient();using var response = await http.HeadAsync( "https://api.github.com/rate_limit");
GitHubApiActionsToolkit.Octokit
The run's context, plus a typed client for the GitHub REST API.
var (owner, repo) = GitHubApi.Context.Repo;var issues = await GitHubApi.CreateClient() .Repos[owner][repo].Issues .GetAsync();
CacheActionsToolkit.Cache
Save and restore dependencies between runs, like actions/cache.
using var cache = Cache.CreateClient();var hit = await cache.RestoreCacheAsync( ["~/.nuget/packages"], primaryKey: "nuget-linux");
ArtifactActionsToolkit.Artifact
Upload files that outlive the job, and download them later.
using var artifacts = Artifact.CreateClient();await artifacts.UploadArtifactAsync( "test-results", Glob.Create("results/*.trx").GlobFiles(), rootDirectory: "results");
ToolCacheActionsToolkit.ToolCache
Download, extract, and cache tools on the runner.
using var tools = ToolCache.CreateClient();var node = tools.Find("node", "22.x");
AttestActionsToolkit.Attest
Sign build provenance for what the workflow produced.
using var attest = Attest.CreateClient();var attestation = await attest.AttestProvenanceAsync( "publish/app");
See a workflow run, start to finish.
Three real workflows: the YAML, the trigger, and what the C# step leaves behind on GitHub.
See it run in your own repo.
Three steps, nothing to install locally. GitHub shows you the file before anything is committed.
GitHub Actions in a minute
- A workflow is a YAML file in
.github/workflows. - The events under
on:start it: a push, a pull request, a schedule, or a manual run. - Each job gets a fresh virtual machine, a runner, and runs its steps in order.
C# without a project
- GitHub saves the
runblock to a file;dotnet run --file {0}runs it. - A full C# program in one file, with no
.csproj. #:lines work like project settings, such as#:sdkfor the toolkit.
-
Create the workflow
-
Commit it
Choose Commit changes in GitHub's editor. The
pushtrigger starts the first run. -
Open the run
Open the latest Hello from C# run. Its job summary shows your heading, and the step log greets you by name.
Open workflow runsAvailable after you enter a repository in step 1.
name: Hello from C#on: [push, workflow_dispatch] # every push, or run it by handpermissions: contents: readjobs: hello: runs-on: ubuntu-latest steps: - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - name: Run inline C# # GitHub saves run: as a file ({0}); dotnet runs it. shell: dotnet run --file {0} run: | #:sdk ActionsToolkit.Sdk@11.0.0 var context = GitHubApi.Context; var (owner, repo) = context.Repo; // Writes to the step log. Core.Info($"Hello from C#, {context.Actor}!"); // Renders on the run's summary page. await Core.Summary .AddMarkdownHeading("Hello from C#") .AddNewLine() .AddRawMarkdown( $"Run #{context.RunNumber} of {owner}/{repo}.") .WriteAsync();- Least privilege Reading the repository is all this needs. Grant more only when a step calls an API that needs it.
-
.NET 11 SDK
File-based apps and
#:sdkneed .NET 11 or later;setup-dotnetinstalls it. - A pinned toolkit Restores the SDK from NuGet and brings every module in by name. Always pin an exact version.
Pass values between C# steps.
Each step runs in its own process, so nothing in memory carries over. Values move through step outputs.
12 linesRuns on push with read access, with .NET 11Collapse 12 lines
name: Handoffon: pushpermissions: contents: readjobs: handoff: runs-on: ubuntu-latest steps: - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - name: Set an output id: first # later steps read its outputs by this id shell: dotnet run --file {0} run: | #:sdk ActionsToolkit.Sdk@11.0.0 await Core.SetOutputAsync("message", "Hello from step one"); - name: Read it as an input shell: dotnet run --file {0} env: INPUT_MESSAGE: ${{ steps.first.outputs.message }} run: | #:sdk ActionsToolkit.Sdk@11.0.0 var message = Core.GetInput("message", required: true); Core.Info($"Step two received: {message}");-
Step one sets an output.
Core.SetOutputAsyncwrites it to the runner, so it outlives the process. -
YAML passes it forward.
Step one's
messageoutput becomes step two'sINPUT_MESSAGEinput. -
Step two reads it.
Core.GetInput("message")picks it up like any action input.
Step two received: Hello from step one
Real jobs, in a page of C#.
When a step outgrows its run block, move the C# into a file in .github/scripts unchanged and run it with dotnet run --file. Same directives and modules, plus editor support and #:include for shared helpers.
#:sdk ActionsToolkit.Sdk@11.0.0using System.Xml.Linq;using ActionsToolkit.Core;using ActionsToolkit.Exec;// Run the tests, but report before failing the step.await Exec.RunAsync( "dotnet", ["test", "--logger", "trx", "--results-directory", "results"], new ExecOptions { IgnoreReturnCode = true });XNamespace trx = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";var tests = Directory.GetFiles("results", "*.trx") .SelectMany(file => XDocument.Load(file).Descendants(trx + "UnitTestResult")) .ToList();var failures = tests .Where(test => test.Attribute("outcome")?.Value is "Failed") .ToList();// Each failure becomes an error annotation on the run page.foreach (var test in failures){ var name = test.Attribute("testName")?.Value; var message = test.Descendants(trx + "Message").FirstOrDefault()?.Value; Core.Error(message ?? "Test failed", new AnnotationProperties { Title = name });}var commit = GitHubApi.Context.Sha?[..7];await Core.Summary .AddMarkdownHeading($"{tests.Count - failures.Count} of {tests.Count} tests passed at {commit}") .AddNewLine() .AddMarkdownList(failures.Select(test => $"`{test.Attribute("testName")?.Value}`")) .WriteAsync();if (failures.Count > 0){ Core.SetFailed($"{failures.Count} tests failed.");}Turn test failures into annotations on the run page and a pass/fail summary.
ExecCore
name: Test reporton: [push, pull_request]permissions: contents: readjobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - run: dotnet run --file .github/scripts/test-report.csNeeds contents: read.
#:sdk ActionsToolkit.Sdk@11.0.0using GitHub.Repos.Item.Item.Issues.Item.Comments;// On pull_request: comment with every file this change touches.// Needs `pull-requests: write` and GITHUB_TOKEN: ${{ github.token }} in env.var context = GitHubApi.Context;var (owner, repo, number) = context.Issue;// A typed REST client: no hand-built URLs or JSON.var github = GitHubApi.CreateClient();var files = await github.Repos[owner][repo].Pulls[(int)number].Files.GetAsync() ?? [];var rows = files .OrderByDescending(file => file.Changes) .Select(file => $"| `{file.Filename}` | +{file.Additions} | -{file.Deletions} |");var body = $""" ### {files.Count} files changed by @{context.Actor} | File | Added | Removed | | --- | ---: | ---: | {string.Join('\n', rows)} """;await github.Repos[owner][repo].Issues[(int)number].Comments .PostAsync(new CommentsPostRequestBody { Body = body });Comment on a pull request with every file it changes.
ExecGitHubApi
name: PR commenton: pull_requestpermissions: contents: read pull-requests: write # post the commentjobs: comment: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - run: dotnet run --file .github/scripts/pr-comment.cs env: GITHUB_TOKEN: ${{ github.token }}Needs pull-requests: write and GITHUB_TOKEN mapped into env.
#:sdk ActionsToolkit.Sdk@11.0.0using ActionsToolkit.Exec;// Draft release notes from conventional commits since the last tag.// Check out with `fetch-depth: 0` so tags and history are available.var context = GitHubApi.Context;var (owner, repo) = context.Repo;var lastTag = await Exec.GetOutputAsync( "git", ["describe", "--tags", "--abbrev=0"], new ExecOptions { IgnoreReturnCode = true, Silent = true });// No tag yet means the whole history.var range = lastTag.ExitCode is 0 ? $"{lastTag.Stdout.Trim()}..HEAD" : "HEAD";var log = await Exec.GetOutputAsync( "git", ["log", range, "--no-merges", "--pretty=format:%h %s"]);var commits = log.Stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries);string Section(string title, string type){ var items = commits .Select(line => (Sha: line[..line.IndexOf(' ')], Subject: line[(line.IndexOf(' ') + 1)..])) .Where(commit => commit.Subject.StartsWith($"{type}:")) .Select(commit => $"- {commit.Subject[(type.Length + 1)..].Trim()} " + $"([{commit.Sha}]({context.ServerUrl}/{owner}/{repo}/commit/{commit.Sha}))"); return items.Any() ? $"### {title}\n\n{string.Join('\n', items)}\n\n" : "";}var notes = Section("Features", "feat") + Section("Fixes", "fix") + Section("Performance", "perf");await Core.SetOutputAsync("notes", notes);await Core.Summary .AddMarkdownHeading($"Release notes for {range}") .AddNewLine() .AddRawMarkdown(notes) .WriteAsync();Group conventional commits since the last tag into release notes.
ExecCore
name: Release noteson: workflow_dispatchpermissions: contents: readjobs: notes: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: fetch-depth: 0 - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - run: dotnet run --file .github/scripts/release-notes.cs id: notes # Publish the C# step's notes output to the run summary. - run: echo "$NOTES" >> "$GITHUB_STEP_SUMMARY" env: NOTES: ${{ steps.notes.outputs.notes }}Needs contents: read and a checkout with fetch-depth: 0 for tags and history.
#:sdk ActionsToolkit.Sdk@11.0.0using ActionsToolkit.Core.Markdown;// Publish the app and fail the build if it outgrows its size budget.var budgetMb = double.TryParse(Core.GetInput("budget-mb"), out var mb) ? mb : 30;await Exec.RunAsync("dotnet", ["publish", "src/App", "-c", "Release", "-o", "publish"]);var files = Directory.GetFiles("publish", "*", SearchOption.AllDirectories) .Select(path => new FileInfo(path)) .OrderByDescending(file => file.Length) .ToList();var sizeMb = files.Sum(file => file.Length) / 1_048_576.0;var overBudget = sizeMb > budgetMb;await Core.Summary .AddMarkdownHeading($"{GitHubApi.Context.Ref} publishes {sizeMb:F1} MB of {budgetMb} MB") .AddNewLine() .AddAlert( overBudget ? "Over budget. Start with the largest files." : "Within budget.", overBudget ? AlertType.Warning : AlertType.Tip) .AddMarkdownList(files.Take(5).Select(file => $"`{file.Name}` {file.Length / 1024:N0} KB")) .WriteAsync();await Core.SetOutputAsync("size-mb", Math.Round(sizeMb, 1));// The summary is already written, so a failed run still explains itself.if (overBudget){ Core.SetFailed($"Publish output is {sizeMb:F1} MB, over the {budgetMb} MB budget.");}Fail the build when the published app outgrows its budget.
ExecCore
name: Size budgeton: [push, pull_request]permissions: contents: readjobs: budget: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - run: dotnet run --file .github/scripts/size-budget.cs env: INPUT_BUDGET-MB: 30 # Core.GetInput("budget-mb")Needs contents: read. The budget comes from the budget-mb input.
#:sdk ActionsToolkit.Sdk@11.0.0// Sign build provenance for a published binary.// Needs `id-token: write`, `attestations: write`, and GITHUB_TOKEN: ${{ github.token }} in env.using var attest = Attest.CreateClient();var attestation = await attest.AttestProvenanceAsync("publish/app");Core.Notice($"Attested publish/app as {attestation.AttestationId}.");Sign build provenance for a binary with the job's OIDC identity.
AttestCore
name: Build provenanceon: push: branches: [main]permissions: contents: read id-token: write # sign with the workflow's OIDC identity attestations: write # store the signed provenancejobs: attest: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-dotnet@v6 with: dotnet-version: 11.0.x - run: dotnet publish src/App -c Release -o publish - run: dotnet run --file .github/scripts/attest.cs env: GITHUB_TOKEN: ${{ github.token }}Needs id-token: write, attestations: write and GITHUB_TOKEN mapped into env.