拉取仓库大家肯定再熟悉不过了,但是你知道怎么用js拉取git文件吗?
让我们一起来学习这个小技能吧!
提取信息
- 根域
- 仓库作者
- 仓库名
- 文件路径
let url = `https://github.com/${author}/${repo}/blob/main/${path}`
ok现在我们有了url,开始下一步吧
Github Api
获取SHA秘钥
这是github公开的接口,只要是public的仓库都是可以拉取的
https://api.github.com/repos/${author}/${repo}/contents/${path}
现在我们可以获取到了SHA指纹,就可以拿到存储在Github上的文件blob对象了
获取blob
获取blob是需要sha的
https://api.github.com/repos/${author}/${repo}/git/blobs/${sha}
现在用刚才获取到的sha试一下
https://api.github.com/repos/caro1xxx/zhihu/git/blobs/7a4a3ea2424c09fbe48d455aed1eaa94d9124835
成功获取到了blob
封装
function getGit(author, repo, path) {
//获取SHA
let data = fetch(
`https://api.github.com/repos/${author}/${repo}/contents/${path}`
)
.then(info => info.json())
.then(info =>
//获取blob
fetch(
`https://api.github.com/repos/${owner}/${repo}/git/blobs/${info.sha}`
)
)
.then(info => info.json
//因为是base64,所有需要decodeing一下
.then(info => atob(info.content));
return data
}
//我获取的就是:https://github.com/caro1xxx/zhihu/blob/main/LICENSE
let res = getgit("caro1xxx", "zhihu", "LICENSE").then(res => { console.log(res) })
最后
就图个新鲜吧,说方便也没有curl方便,说灵活,我还是觉得Git灵活(狗头)
权当奇技淫巧^v^