2016-12-24 63 views
1

我想开发一个windows表单应用程序,它可以使用Octokit在GitHub存储库中创建,更新和删除文件。使用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)); 

正如你所看到的,在这种情况下,我一定要得到,因为对于“UpdateFileRequest”要求的SHA值,

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

如何我可以从GitHub收到我的文件的Sha值吗?

我下面this的教程,但是当我尝试“createChangeSet.Content.Sha”(不注释掉createChangeSet),它绘制一条红线下方的“内容”,并说,

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值,以便我可以使用该值来更新文件?

回答

2

我有同样的问题,并得到沙你需要先获得现有的文件,并与此文件,你也得到最后一个提交沙,可用于更新文件。

完整的示例代码:

  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)); 
      } 

我不知道是否有更好的方式来做到这一点 - 如果没有找到搜索的文件则抛出异常。

但似乎这样工作。

+0

此解决方案完美运行。非常感谢你! – coder

+0

但是,如何以同样的方式从GitHub获取文件的内容? – coder

+0

内容应该在那里 - 请参阅GitHub Api文档:https://developer.github.com/v3/repos/contents/#get-contents –