我正在尝试开发一个 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/