我正在尝试使用以下命令创建github gist
curl -X POST -d '{"public":true,"files":{"test.txt":{"content":"String file contents"}}}' -u mgarciaisaia:mypassword https://api.github.com/gists我应该如何编辑该命令,使其将本地计算机上的文件上载到新的gist,而不是从命令行获取字符串中的内容?
发布于 2021-07-21 05:47:14
您可以使用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"
}
}
}或者,对于公共gis:
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完成了!
https://stackoverflow.com/questions/68460308
复制相似问题