Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

git - How do I get the "sha" parameter from GitHub API without downloading the whole file?

I have been trying to update a file in a GitHub repository by using GitHub API while having only a path to that file. My plan was first, get the file contents like described here: https://developer.github.com/v3/repos/contents/ , and then use the "sha" field to "update a file".

It worked fine just as described in the answer here How to find a Github file 's SHA blob .

However, using GET /repos/:owner/:repo/contents/:path , downloads the whole file, as a field in the returned JSON, which is inefficient. So, my question is: is there a way to get just the "sha" field without downloading the entire file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could leverage the <rev>:<path> extended SHA-1 syntax to retrieve some meta data about the Blob from its parent Tree.

For instance, provided you work with the libgit2/libgit2sharp repository, and you'd like to retrieve the sha of the file Lib/MoQ/Moq.license.txt from the master branch:

  • Leverage the GitHub Trees API to retrieve the content of the Tree matching the Lib/MoQ parent directory
  • Retrieve from the returned Json payload the sha of the blob which path is Moq.license.txt
  • Make sure to url encode the the <rev>:<path> segment as it contains forward slashes

In brief:

The example link above will return the following payload

{
  "sha": "2f2c87728225f9cbb6e2d8c5997b6031e72ddca4",
  "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/trees/2f2c87728225f9cbb6e2d8c5997b6031e72ddca4",
  "tree": [
    {
      "path": "Moq.dll",
      "mode": "100644",
      "type": "blob",
      "sha": "bdd4235f215541017a9f37b6155f18e309573838",
      "size": 659968,
      "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/blobs/bdd4235f215541017a9f37b6155f18e309573838"
    },
    {
      "path": "Moq.license.txt",
      "mode": "100644",
      "type": "blob",
      "sha": "c9216ccba318292d76fd308f232e7871bbbe77be",
      "size": 1748,
      "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/blobs/c9216ccba318292d76fd308f232e7871bbbe77be"
    },
    {
      "path": "Moq.xml",
      "mode": "100644",
      "type": "blob",
      "sha": "160c1b5165fd967f4c79bc6043f0cc2ec28710d8",
      "size": 314572,
      "url": "https://api.github.com/repos/libgit2/libgit2sharp/git/blobs/160c1b5165fd967f4c79bc6043f0cc2ec28710d8"
    }
  ],
  "truncated": false
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...