Microsoft.DotNet.GitAutomation is a library for declaratively managing
pull requests and (eventually) issues.
This pattern is most useful for automation that repeatedly opens or updates similar pull requests or issues, like dependency or version updates.
| Feature | GitHub | Azure DevOps |
|---|---|---|
| Pull requests | ✅ | ✅ |
| Issues | - | - |
| Groups of issues | - | - |
The feature matrix will be filled out incrementally (as needed) in order to accomplish #1658.
This example creates or updates a pull request on GitHub.
using Microsoft.DotNet.GitAutomation;
using Microsoft.DotNet.GitAutomation.GitHub;
var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN")
?? throw new InvalidOperationException();
var identity = new AutomationIdentity(
"automation-bot",
"[email protected]");
var accessProvider = new StaticGitHubAccessProvider(token, identity);
var gitHub = new GitHubPullRequestEndpoint(
accessProvider,
new GitHubRepo("dotnet", "example"));
PullRequestDefinition definition = new PullRequestDefinition(
Key: "automation/update-generated-files",
Title: "Update generated files",
Body: "Updates files generated by the build.",
TargetBranch: "main",
ApplyChanges: async (git, cancellationToken) =>
{
string path = Path.Join(git.WorkspaceDirectory, "generated.txt");
await File.WriteAllTextAsync(path, "new content", cancellationToken);
await git.CommitAsync("Update generated.txt", cancellationToken);
});
PullRequestManager manager = new PullRequestManager();
PullRequestResult result = await manager.CreateOrUpdateAsync(definition, gitHub);
Console.WriteLine($"{result.Action}: {result.Url}");The first run opens a pull request if the callback changes any files. Later
runs find the open pull request with the same Key and update it.
For a fixed access token, use StaticGitHubAccessProvider. Pass the Git author
name and email that the automation will use for its commits.
AutomationIdentity identity = new AutomationIdentity(
"automation-bot",
"[email protected]");
IGitHubAccessProvider accessProvider = new StaticGitHubAccessProvider(
token,
identity);To open pull requests from a fork, pass both repositories:
GitHubPullRequestEndpoint endpoint = new GitHubPullRequestEndpoint(
accessProvider,
upstream: new GitHubRepo("dotnet", "example"),
fork: new GitHubRepo("automation-bot", "example"));The access provider must have permissions to both the upstream repository and the fork.
GitHubAppAccessProvider uses a GitHub App private key stored in Azure Key
Vault. The Azure identity must have the Key Vault Crypto User role on the
Key Vault. The GitHub App must be installed on every repository that it uses.
using Azure.Identity;
using Azure.Security.KeyVault.Keys.Cryptography;
using Microsoft.DotNet.GitAutomation.GitHub;
var keyUri = new Uri("https://your-vault.vault.azure.net/keys/github-app-key");
// Use any Azure.Identity credential here:
var credential = new AzureCliCredential();
var cryptographyClient = new CryptographyClient(keyUri, credential);
var accessProvider = new GitHubAppAccessProvider(githubAppClientId, cryptographyClient);GitHubAppAccessProvider automatically determines the correct login and email
address to use for git operations.
Create an Azure DevOps client with the organization, project, and access token. Pass the same access token to the pull request endpoint so Git can clone and push.
using Microsoft.DotNet.GitAutomation;
using Microsoft.DotNet.GitAutomation.AzureDevOps;
string token = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN")
?? throw new InvalidOperationException();
var identity = new AutomationIdentity(
"automation-bot",
"[email protected]");
using var httpClient = new AzureDevOpsClient(
organization: "your-organization",
project: "your-project",
accessToken: token); // token used for HTTP operations
var azureDevOps = new AzureDevOpsPullRequestEndpoint(
httpClient,
"your-repository",
token, // token used for git operations
identity);
var manager = new PullRequestManager();
var result = await manager.CreateOrUpdateAsync(definition, azureDevOps);The token authenticates Azure DevOps API requests and Git operations. In Azure
Pipelines, map System.AccessToken to the SYSTEM_ACCESSTOKEN environment
variable.
A PullRequestDefinition describes the pull request and the changes that
produce it.
Key is the source branch name. The library uses it to find an existing open
pull request. Use a stable key for repeated runs. Use different keys when the
same job can have more than one open pull request.
A key may contain ASCII letters, digits, underscores, dashes, periods, and
slashes. It cannot start with a dash. Empty path parts and parts that end in
.lock are not valid.
Title, Body, and TargetBranch are the desired pull request properties.
The library updates these properties when they change.
ApplyChanges is the callback where apps should make changes to the repo.
Call CommitAsync when you want to create a commit. You may create more than
one commit. After ApplyChanges finishes, the manager commits any remaining
changes with the pull request title as the commit message.
The library deletes the temporary working directory after the run.
PullRequestUpdateStrategy.Append clones the existing pull request branch. New
commits are added directly on top of the pull request branch. This is the
default.
PullRequestUpdateStrategy.Replace applies the changes directly on top of the
target branch and force-pushes the result to the pull request branch.
await manager.CreateOrUpdateAsync(
definition,
endpoint,
updateStrategy: PullRequestUpdateStrategy.Replace);If there is no diff after applying changes, then nothing will happen.
A foreign commit is a commit made by anyone other than the automation identity.
ForeignCommitPolicy.Proceed applies the selected update strategy even when
the branch contains foreign commits. This is the default.
ForeignCommitPolicy.Stop leaves the branch and pull request unchanged when it
finds a foreign commit.
await manager.CreateOrUpdateAsync(
definition,
endpoint,
updateStrategy: PullRequestUpdateStrategy.Append,
onForeignCommits: ForeignCommitPolicy.Stop);Use Stop when people may add commits to the automation branch and those
commits must not be replaced or extended.
GitAutomation includes ServiceCollection extension methods to make
registration more convenient.
The extension methods add PullRequestManager, logging, a process runner, and
the selected host endpoint.
ServiceCollection services = new ServiceCollection();
services.AddGitHubPullRequestAutomation(
new GitHubRepo("dotnet", "example"),
identity,
githubToken);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
var manager = serviceProvider.GetRequiredService<PullRequestManager>();
var endpoint = serviceProvider.GetRequiredService<GitHubPullRequestEndpoint>();Use the overload that accepts IGitHubAccessProvider for GitHub App or custom
authentication.
string token = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN")
?? throw new InvalidOperationException();
var identity = new AutomationIdentity(
"automation-bot",
"[email protected]");
ServiceCollection services = new ServiceCollection();
services.AddAzureDevOpsPullRequestAutomation(
"your-organization",
"your-project",
"your-repository",
identity,
token);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
var manager = serviceProvider.GetRequiredService<PullRequestManager>();
var endpoint =
serviceProvider.GetRequiredService<AzureDevOpsPullRequestEndpoint>();To replace the default process runner, register IProcessRunner before the
automation services:
services.AddSingleton<IProcessRunner, CustomProcessRunner>();
services.AddGitHubPullRequestAutomation(/* ... */);