我正在创建一个计划工具,用于每天将更改合并到我的GitHub存储库。为此,我需要工具执行以下函数
- 签出一个分支(工作分支),并将其与目标分支的最新更改一起拉出
- 在工作分支中进行需要合并到目标分支中的更改。
- 将修改后的文件提交到远程工作分支
- 创建从工作分支到目标分支的拉取请求
- 合并已创建的pull request。
我能够使用PowerShell命令和GitHub访问令牌实现上面的前3点。我被困在创建拉请求和合并它们的部分。我已经按照下面的文档进行了相同的操作,但是API调用返回Not found.
https://docs.github.com/en/rest/reference/pulls create-a-pull-request
基于上述文档使用的示例代码
RestRequest restRequest = new RestRequest("repos/" + GitHubUserId + "/" + "working-repository", Method.POST);
restRequest.Parameters.Clear();
restRequest.AddHeader("accept", "application/vnd.github.v3+json");
restRequest.AddParameter("head", sourceBranch);
restRequest.AddParameter("base", targetBranch);
restRequest.AddParameter("title", title);
restRequest.AddParameter("body", description);
https://github.com/octokit/octokit.net/blob/main/docs/demos/exploring-pull-requests.md
基于上述文档使用Octokit包的示例代码。
GitHubClient gitHubClient = new GitHubClient(new ProductHeaderValue(ConfigurationManager.AppSettings["GitHubUserId"].ToString(), "v1.0.0"));
gitHubClient.Credentials = new Credentials(ConfigurationManager.AppSettings["GitHubAccessToken"].ToString());
NewPullRequest newPullRequest = new NewPullRequest(title, sourceBranch, targetBranch);
var octokitRepo = await gitHubClient.Repository.Get("Organization", "working-reposiory");
var pullRequest = await gitHubClient.PullRequest.Create("Organization", "working-reposiory", newPullRequest);
接下来我可以尝试什么?
来晚了一点,但应该是你所需要的,对其他人来说也是如此。
public async Task DoItAll(string personalAccessToken)
{
var ownerName = "Organization";
var repositoryName = "Repository Name";
var defaultBranchName = "heads/main";
var featureBranchName = "refs/heads/feature-branch";
var client = new GitHubClient(new ProductHeaderValue("AppName"))
{
Credentials = new Credentials(personalAccessToken)
};
var repo = await client.Repository.Get(ownerName, repositoryName);
var defaultBranch = await client.Git.Reference.Get(ownerName, repositoryName, defaultBranchName);
var featureBranch = await client.Git.Reference.Create(ownerName,
repositoryName,
new NewReference(featureBranchName, defaultBranch.Object.Sha));
//Must commit at least one change to feature branch prior to creating PR, code omitted
var pr = await client.PullRequest.Create(repo.Id,
new NewPullRequest("PR Title", featureBranch.Ref, defaultBranch.Ref));
var newMerge = new NewMerge(defaultBranch.Ref, featureBranch.Ref);
await client.Repository.Merging.Create(repo.Id, newMerge);
}