Updating a file in GitHub repository using Octokit

烈酒焚心 提交于 2019-12-04 17:04:48

I had the same problem and to get the sha you will need to get the existing file first and with this file you also get the last commit sha, which can be used to update the file.

Full demo code:

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

I'm not sure if there is a better way to do it - if the searched file is not found an exception is thrown.

But it seems to work that way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!