使用文件创建 Github gist,使用 Gist API

问题描述

我正在尝试使用以下命令制作 github gist

curl -X POST -d '{"public":true,"files":{"test.txt":{"content":"String file contents"}}}' -u mgarciaisaia:mypassword https://api.github.com/gists

我应该如何编辑命令,使其将本地计算机上的文件上传到新的 gist,而不是从命令行获取字符串中的内容

解决方法

您可以使用 jq 生成合适的负载。假设您的文件 myfile 如下所示:

#!/usr/bin/env bash

sed '
    s/://            # Drop colon
    s/^/Package: /   # Prepend with "Package: "
    N                # Append next line to pattern space
    s/\n/ | New: /   # Replace newline with " | New: "
    N                # Append next line to pattern space
    s/\n/ | Old: /   # Replace newline with " | Old: "
' updates.txt

带有 sed 命令的 shell 脚本,包括制表符缩进、转义字符等。要将其转换为 JSON 字符串:

jq --raw-input --slurp '.' myfile

导致

"#!/usr/bin/env bash\n\nsed '\n\ts/://            # Drop colon\n\ts/^/Package: /   # Prepend with \"Package: \"\n\tN                # Append next line to pattern space\n\ts/\\n/ | New: /   # Replace newline with \" | New: \"\n\tN                # Append next line to pattern space\n\ts/\\n/ | Old: /   # Replace newline with \" | Old: \"\n' updates.txt\n"

这是一个长字符串,可以安全地转义以用作 JSON 字符串。

现在,为了将其转化为我们可以在 API 调用中用作负载的格式:

jq --raw-input --slurp '{files: {myfile: {content: .}}}' myfile

哪个打印

{
  "files": {
    "myfile": {
      "content": "#!/usr/bin/env bash\n\nsed '\n\ts/://            # Drop colon\n\ts/^/Package: /   # Prepend with \"Package: \"\n\tN                # Append next line to pattern space\n\ts/\\n/ | New: /   # Replace newline with \" | New: \"\n\tN                # Append next line to pattern space\n\ts/\\n/ | Old: /   # Replace newline with \" | Old: \"\n' updates.txt\n"
    }
  }
}

或者,对于公共地理信息系统:

jq --raw-input --slurp '{public: true,files: {myfile: .}}' myfile

我们可以通过管道将其传递给 curl 并告诉它使用 @- 从标准输入读取有效负载:

jq --raw-input --slurp '{public: true,files: {myfile: .}}' myfile \
    | curl \
        https://api.github.com/gists \
        --header 'Accept: application/vnd.github.v3+json' \
        --header "Authorization: token $(< ~/.token)" \
        --data @-

这使用个人访问令牌进行身份验证,该令牌应位于文件 ~/.token 中。


如果您使用 GitHub CLI,它会变得简单得多:

gh gist create --public myfile

大功告成!