如何使用GitHub DB API提交对文件的更改

时间:2013-10-10 00:10:35

标签: c# .net git github github-api

我正在尝试使用c#使用GitHub DB API更新文件。执行此操作的过程在此处http://developer.github.com/v3/git/定义,如下所示

  • 获取当前提交对象
  • 检索它指向的树
  • 检索树对该特定文件路径的blob对象的内容
  • 以某种方式更改内容并使用该新内容发布新的blob对象,然后获取blob SHA
  • 发布一个新的树对象,该文件路径指针替换为新的blob SHA *获取树SHA回来
  • 使用当前提交SHA作为父树和新树SHA创建一个新提交对象,获取提交SHA
  • 更新分支的引用以指向新提交SHA

然而,当我到达

时,它失败了
  

更新分支的引用以指向新提交SHA

即行

var updateReferenceResponse = Patch<UpdateReferenceResponse>("git/refs/heads/master", updateReferenceRequest);

响应失败

<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>

以下是我尝试调用http://developer.github.com/v3/git/refs/#update-a-reference

的具体API

以下是代码

的主要工作方式
[Test]
public void UpdateFileUsingGithubDataApi()
{
    var branch = GetUrlResponse<BranchResponse>("branches/master");
    var currentCommitSha = branch.commit.sha;

    var tree = GetUrlResponse<CommitResponse>("git/commits/" + currentCommitSha).tree;
    var createBlob = new CreateBlobRequest
                     {
                         content = "sdkfn",
                         encoding = "utf-8"
                     };
    var blobResponse = Post<CreateBlobResponse>("git/blobs", createBlob);
    var blobSha = blobResponse.sha;
    var createTreeRequest = new CreateTreeRequest
                            {
                                base_tree = tree.sha,
                                tree = new List<CreateTreeRequest.Tree>
                                       {
                                           new CreateTreeRequest.Tree
                                           {
                                               path = "README.md",
                                               mode = "100644",
                                               type = "blob",
                                               sha = blobSha
                                           }
                                       }
                            };

    var treeResponse = Post<CreateTreeResponse>("git/trees", createTreeRequest);

    var createCommitRequest = new CreateCommitRequest
                              {
                                  parent = new List<string>
                                           {
                                               currentCommitSha
                                           },
                                  message = "foo",
                                  tree = treeResponse.sha
                              };
    var commitResponse = Post<CreateCommitResponse>("git/commits", createCommitRequest);

    var updateReferenceRequest = new UpdateReferenceRequest
                                 {
                                     sha = commitResponse.sha
                                 };
    var updateReferenceResponse = Patch<UpdateReferenceResponse>("git/refs/heads/master", updateReferenceRequest);
}

TResponse Post<TResponse>(string suffix, object value)
{
    return Send<TResponse>(suffix, value, "Post");
}


TResponse Patch<TResponse>(string suffix, object value)
{
    return Send<TResponse>(suffix, value, "Patch");
}

TResponse Send<TResponse>(string suffix, object value, string method)
{
    var serializeObject = JsonConvert.SerializeObject(value, Formatting.Indented);
    var sourceUrl = string.Format("https://api.github.com/repos/{0}/{1}/{2}", UserName, repo, suffix);
    Debug.WriteLine("\r\n{0}ing to {1} with data\r\n{2}", method, sourceUrl, serializeObject);
    var webRequest = WebRequest.Create(sourceUrl);
    webRequest.Method = method;
    AddAuth(webRequest);
    var requestStream = webRequest.GetRequestStream();
    using (var streamWriter = new StreamWriter(requestStream))
    {
        streamWriter.Write(serializeObject);
    }
    try
    {
        using (var webResponse = webRequest.GetResponse())
        {
            var text = webResponse.GetResponseStream().ReadToEnd();

            Debug.WriteLine("response:\r\n" + text.GetPrettyPrintedJson());
            return JsonConvert.DeserializeObject<TResponse>(text);
        }
    }
    catch (WebException exception)
    {
        var readToEnd = exception.Response.GetResponseStream().ReadToEnd();
        Debug.WriteLine("failed with response:\r\n" + readToEnd);
        throw new Exception(readToEnd);
    }
}

TResponse GetUrlResponse<TResponse>(string suffix)
{
    var sourceUrl = string.Format("https://api.github.com/repos/{0}/{1}/{2}", UserName, repo, suffix);
    var webRequest = WebRequest.Create(sourceUrl);
    Debug.WriteLine("\r\nrequesting " + sourceUrl);
    AddAuth(webRequest);
    using (var webResponse = webRequest.GetResponse())
    {
        var text = webResponse.GetResponseStream().ReadToEnd();
        Debug.WriteLine("response:\r\n"+ text.GetPrettyPrintedJson());
        return JsonConvert.DeserializeObject<TResponse>(text);
    }
}

void AddAuth(WebRequest webRequest)
{
    if (UserName != null && Password != null)
    {
        var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", UserName, Password)));
        webRequest.Headers.Add("Authorization", string.Format("Basic {0}", token));
    }
}

以下是http对话的成绩单

requesting https://api.github.com/repos/simoncropp/test/branches/master
response:
{
  "name": "master",
  "commit": {
    "sha": "a4447748c9cd36601127e3a6143348a1695cc2e8",
    "commit": {
      "message": "Initial commit",
      "tree": {
        "sha": "5b3438cf3aca03901bdb2ae1722bc7e05738a7fe",
      },
      "comment_count": 0
    },
  },
}

requesting https://api.github.com/repos/simoncropp/test/git/commits/a4447748c9cd36601127e3a6143348a1695cc2e8
response:
{
  "sha": "a4447748c9cd36601127e3a6143348a1695cc2e8",
  "tree": {
    "sha": "5b3438cf3aca03901bdb2ae1722bc7e05738a7fe",
  },
  "message": "Initial commit",
  "parents": []
}

Posting to https://api.github.com/repos/simoncropp/test/git/blobs with data
{
  "content": "sdkfn",
  "encoding": "utf-8"
}
response:
{
  "sha": "2b664114096f7ff36664e381c5fbd0030f47009c",
}

Posting to https://api.github.com/repos/simoncropp/test/git/trees with data
{
  "base_tree": "5b3438cf3aca03901bdb2ae1722bc7e05738a7fe",
  "tree": [
    {
      "path": "README.md",
      "mode": "100644",
      "type": "blob",
      "sha": "2b664114096f7ff36664e381c5fbd0030f47009c"
    }
  ]
}
response:
{
  "sha": "fd1379d51016989a615acf79409256849dc8ea7f",
  "tree": [
    {
      "mode": "100644",
      "type": "blob",
      "sha": "bdc3535f745bc86966fb24c67d252c3ea68e8e03",
      "path": ".gitignore",
      "size": 1522,
    },
    {
      "mode": "100644",
      "type": "blob",
      "sha": "e0369aaa94e2bc8dce560c0ae0669d74204602d5",
      "path": "LICENSE",
      "size": 1078,
    },
    {
      "mode": "100644",
      "type": "blob",
      "sha": "2b664114096f7ff36664e381c5fbd0030f47009c",
      "path": "README.md",
      "size": 5,
    }
  ]
}

Posting to https://api.github.com/repos/simoncropp/test/git/commits with data
{
  "message": "foo",
  "tree": "fd1379d51016989a615acf79409256849dc8ea7f",
  "parent": [
    "a4447748c9cd36601127e3a6143348a1695cc2e8"
  ]
}
response:
{
  "sha": "f66832493d22c58a6dd9d41b65504c1e9c901d7a",
  "tree": {
    "sha": "fd1379d51016989a615acf79409256849dc8ea7f",
  },
  "message": "foo",
  "parents": []
}

Patching to https://api.github.com/repos/simoncropp/test/git/refs/heads/master with data
{
  "sha": "f66832493d22c58a6dd9d41b65504c1e9c901d7a"
}
failed with response:
<html><body><h1>502 Bad Gateway</h1>
The server returned an invalid or incomplete response.
</body></html>

1 个答案:

答案 0 :(得分:2)

Posting to https://api.github.com/repos/simoncropp/test/git/commits with data
{
  "message": "foo",
  "tree": "fd1379d51016989a615acf79409256849dc8ea7f",
  "parent": [
    "a4447748c9cd36601127e3a6143348a1695cc2e8"
  ]
}

文档在这里需要parents参数,而不是parent

response:
{
  "sha": "f66832493d22c58a6dd9d41b65504c1e9c901d7a",
  "tree": {
    "sha": "fd1379d51016989a615acf79409256849dc8ea7f",
  },
  "message": "foo",
  "parents": []
}

如果没有它,你会获得一个空的父提交数组,而糟糕的事情将会发生。