json - 如何从 Bash 使用 GitHub API?

标签 json bash github github-api

我有一个存储库,我正在为其编写 Bash 中的“安装脚本”。我的计划是将我想要安装的所有脚本都放在存储库根目录下的 scripts/ 目录中,并在最顶部放置一个名为 install 的脚本。

我的计划是让用户运行这样的程序:

curl -sSL http://github.com/me/repo/raw/master/install | bash

安装脚本将下载 GitHub 目录中的所有脚本,并将它们放在适当的位置。

我的问题是,我应该如何从 Bash 中执行此操作?例如,GitHub 以 JSON 格式返回其 API 响应,那么我将如何解析脚本中的响应内容?有什么方法可以更改响应格式,使其可以被 Bash 解析? (如果您为我的特定用例提供了一个清晰的示例,则加分。)

谢谢。

最佳答案

您不必为此使用 Github API。您可以指示用户获取原始文件:

curl -sSL https://raw.githubusercontent.com/me/repo/master/install | bash

这是一个 common idiom ,显然。


顺便说一句,我更喜欢使用进程替换:

bash <(curl -sSL https://raw.githubusercontent.com/me/repo/master/install)

如果您想使用标准输入,它不会受到伤害。


如果我误解了,你打算使用 API 获取脚本列表,这将是一个多步骤过程:

  1. https://api.github.com/repos/user/repo/branches/masterurl 属性获取分支树。
  2. 在该树的条目中查找目录 (https://api.github.com/repos/user/repo/git/trees/hash) - 查找类型的实体路径脚本
  3. 然后在 that 树中查找 blob 类型的条目(https://api.github.com/repos/user/repo/git/trees/散列)
  4. 获取每个 blob,(https://api.github.com/repos/user/repo/git/blobs/hash),然后是 base64-解码 content 属性(编码也在 encoding 属性中指定,因此也需要处理)。

在你的 scripts 目录中维护一个脚本列表,使用 curl -sSL https://raw.githubusercontent.com/me 获取它会容易得多/repo/master/scripts/list-of-scripts 然后 curl 它们。然后你可以这样做,例如:

curl -sSL https://raw.githubusercontent.com/me/repo/master/scripts/list-of-scripts |
  xargs -L1 -i{} curl -sSL https://raw.github.com/me/repo/master/scripts/{}

如果您真的必须使用 API,最简单的方法是使用 the jq tool .在您的脚本中下载它(根据需要更改版本、操作系统和体系结构):

curl -sSL https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 > jq
chmod +x jq

现在开始漫长的折磨之旅:

tree_url=$(curl -sSL https://api.github.com/repos/user/repo/branches/master | 
  ./jq -r '.commit.commit.tree.url')
script_tree=$(curl -sSL "$tree_url" | 
  ./jq -r '.tree[] | select(.type == "tree" and .path == "scripts") | .url')
curl -sSL "$script_tree" | 
  ./jq -r '.tree[] | select(.type == "blob") | .url' | 
   xargs curl -sSLO

现在对每个新下载的文件运行 base64 -d(您可以使用循环代替 xargs 以使其更容易)。

或者,对于最后一步,您可以:

curl -sSL "$script_tree" | 
  ./jq -r '.tree[] | select(.type == "blob") | .path' |
  xargs -L1 -i{} curl -sSLO https://raw.githubusercontent.com/me/repo/master/scripts/{}

关于json - 如何从 Bash 使用 GitHub API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421354/

相关文章:

python - 如何使用 eve 从同一个键请求多个值

json - 使用 javax.json 从 JSON 字符串到 Java 对象

php 在前台运行另一个脚本

linux - linux shell脚本中for循环的语法

Github Actions 在部署之前替换字符串

javascript - Node.js - JSON.parse - 将 Node 添加到结果中

jquery - JSON.stringify 数组产生双括号

linux - 从 arg 3 开始加入 bash 剩余参数

GitHub Actions - 由合并到主分支的拉取请求触发的运行操作

git - 如何将提交恢复为分支中的新提交