gpt4 book ai didi

c# - 使用 Octokit 更新 GitHub 存储库中的文件

转载 作者:太空狗 更新时间:2023-10-29 14:43:44 30 4
gpt4 key购买 nike

我正在尝试开发一个 Windows 窗体应用程序,它可以使用 Octokit 在 GitHub 存储库中创建、更新和删除文件。

 public Form1()
{
InitializeComponent();

var ghClient = new GitHubClient(new ProductHeaderValue("Octokit-Test"));
ghClient.Credentials = new Credentials("-personal access token here-");

// github variables
var owner = "username";
var repo = "repository name";
var branch = "master";

// create file
//var createChangeSet = ghClient.Repository.Content.CreateFile(owner,repo,"path/file2.txt",new CreateFileRequest("File creation", "Hello World!", branch));

// update file
var updateChangeSet = ghClient.Repository.Content.UpdateFile(owner, repo,"path/file2.txt", new UpdateFileRequest("File update","Hello Universe!", "SHA value should be here", branch));

}

首先,我设法创建了一个功能齐全的文件(检查注释掉的代码)。然后我尝试使用更新该文件,

var updateChangeSet = ghClient.Repository.Content.UpdateFile(owner, repo,"path/file2.txt", new UpdateFileRequest("File update","Hello Universe!", "SHA value should be here", branch));

如您所见,在这种情况下,我必须获取 sha 值,因为“UpdateFileRequest”的要求是,

UpdateFileRequest(string message, string content, string sha, string branch)

我如何从 GitHub 接收我的文件的这个 Sha 值?

我正在关注 this教程,但是当我尝试“createChangeSet.Content.Sha”(没有注释掉 createChangeSet)时,它在“Content”下面画了一条红线并说,

Task<RepositoryChangeSet> does not contain a definition for 'Content' and no extention method 'Content' accepting a first argument of type Task<RepositoryChangeSet> could be found

我看了GitHub Documentation它说我应该使用,

GET /repos/:owner/:repo/contents/:path

返回存储库中文件或目录的内容,所以我假设我将能够通过这种方式获得 sha 值。

如何实现此方法以接收存储库中我的文件的 sha 值,以便我可以使用该值来更新文件?

最佳答案

我遇到了同样的问题,要获取 sha,您需要先获取现有文件,使用此文件,您还可以获得最后一次提交的 sha,可用于更新文件。

完整的演示代码:

            var ghClient = new GitHubClient(new ProductHeaderValue("Octokit-Test"));
ghClient.Credentials = new Credentials("//...//");

// github variables
var owner = "owner";
var repo = "repo";
var branch = "branch";

var targetFile = "_data/test.txt";

try
{
// try to get the file (and with the file the last commit sha)
var existingFile = await ghClient.Repository.Content.GetAllContentsByRef(owner, repo, targetFile, branch);

// update the file
var updateChangeSet = await ghClient.Repository.Content.UpdateFile(owner, repo, targetFile,
new UpdateFileRequest("API File update", "Hello Universe! " + DateTime.UtcNow, existingFile.First().Sha, branch));
}
catch (Octokit.NotFoundException)
{
// if file is not found, create it
var createChangeSet = await ghClient.Repository.Content.CreateFile(owner,repo, targetFile, new CreateFileRequest("API File creation", "Hello Universe! " + DateTime.UtcNow, branch));
}

我不确定是否有更好的方法 - 如果找不到搜索到的文件,则会抛出异常。

但它似乎是这样工作的。

关于c# - 使用 Octokit 更新 GitHub 存储库中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41316067/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com