【问题标题】:get file as text from github v3 api using bash使用 bash 从 github v3 api 获取文件作为文本
【发布时间】:2018-05-06 02:56:25
【问题描述】:

我正在尝试使用 get contents api 从我们的 GitHub 获取配置文件。

这将返回一个 JSON,其中包含编码为 base64 字符串的文件内容。

我想以文本形式获取它

我已采取的步骤

  1. 获取初始 api 响应:
    curl -H 'Authorization: token MY_TOKEN' \ https://github.com/api/v3/repos/MY_OWNER/MY_REPO/contents/MY_FILE
    这将返回带有字段 "content": "encoded content ..."的 JSON 响应

  2. 获取编码字符串:
    添加<prev command> | grep -F "content\":"
    这将获取内容,但仍有"content": 字符串、" 字符和末尾的逗号

  3. 删减额外内容:
    <prev command> | cut -d ":" -f 2 | cut -d "\"" -f 2

  4. 解码:
    <prev command | base64 --decode>

最终命令:
curl -H 'Authorization: token MY_TOKEN' \ https://github.com/api/v3/repos/MY_OWNER/MY_REPO/contents/MY_FILE | \ grep -F "content\":" | cut -d ":" -f 2 | cut -d "\"" -f 2 | base64 --decode

问题:

  1. 生成的字符串(在base64 --decode 之前)在在线解码器中解码(不太好 -> 参见下一项),但在 bash 中无法解码。响应是

    “输入流中的字符无效。”

  2. 解码online decoder 中的字符串时,文件的某些(不是全部)是乱码,而不是原始文本。我已经尝试了所有可用的字符集。

注意事项:

  1. 我尝试使用 sed 's/..$//' 删除最后 2 个(换行符)字符,但这没有任何效果。
  2. 如果我用鼠标选择输出并将其复制粘贴到echo MY_ECODED_STRING_PASTED_HERE | base64 --decode命令,它与在线工具的效果相同,即解码为乱码。

【问题讨论】:

  • 为此使用 Bash 可能会给您带来比您想要的更多的白发。但首先,将 ad hoc 管道替换为适当的 JSON 处理器,例如 jq
  • 区域设置将影响哪些字符被认为是有效的。在脚本开头附近尝试 export LC_ALL=C 以强制执行传统的 POSIX byte=character 语义。
  • 导出 LC_ALL=C 无效。
  • 谷歌搜索错误消息表明输入实际上并不完全是base64。参见例如lists.jboss.org/pipermail/apiman-user/2015-October/000365.html -- 没有代表性样本,很难说到底有什么问题。
  • echo moo | base64 --decode >/dev/null 工作正常,而 echo moo.bar | base64 --decode >/dev/null 让我得到“输入流中的无效字符”。为了记录,有效的 base64 是字母、数字和几个数学符号(+/= 在流的末尾用于填充)。

标签: bash base64 github-api


【解决方案1】:

根据tripleee的建议,我已将提取方法切换为jq

file=randomFileName74894031264.txt

curl -H 'Authorization: token MY_TOKEN' https://github.com/api/v3/repos/MY_OWNER/MY_REPO/contents/MY_FILE > "$file"

encoded_str=($(jq -r '.content' "$file"))

echo "$encoded_str" | base64 -D
rm -f "$file"

这在从命令行运行时有效,但在作为脚本运行时标准输出不会刷新,我们只获取文件的前几行。

当我正式确定一个通用脚本时,我会更新这个答案。

【讨论】:

  • 你不需要临时文件,curl | jq -r .content | base64 -D 应该这样做。
【解决方案2】:

将标题 Accept: application/vnd.github.VERSION.raw 添加到 GET。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 2022-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
相关资源
最近更新 更多