github-api - 如何获取 Linux 上 GitHub 存储库的所有分支的列表?
问题描述
我想有一种简单的、非交互式的方式来获取 GitHub 存储库的分支列表。
就我个人而言,它必须至少在 Linux 上运行。
解决方案
从 bash 脚本中使用 GraphQL (GiHub API v4),使用 cURL:
#!/bin/bash
# Returns a list of all forks of a github repo.
# See the output of "$0 -h" for more details.
set -e
# initial default values
access_token=""
repo_owner=$USER
repo_name=$(basename $(pwd))
res_file=res.json
function print_help() {
echo "Returns a list of all forks of a github repo."
echo
echo "Usage:"
echo " `basename $0` [OPTIONS]"
echo "Options:"
echo " -h, --help Show this help message"
echo " -o, --owner <string> Name of the GitHub user or organization of the original repo"
echo " -r, --repo <string> Name of the GitHub original repo"
echo " -t, --token <string> GitHub personal access token, required for authentication"
echo " To get one, see: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line"
}
# read command-line args
POSITIONAL=()
while [[ $# -gt 0 ]]
do
arg="$1"
shift
case "${arg}" in
-h|--help)
shift # past argument
print_help
exit 0
;;
-o|--owner)
repo_owner="$1"
shift # past argument
;;
-r|--repo)
repo_name="$1"
shift # past argument
;;
-t|--token)
access_token="$1"
shift # past argument
;;
*) # non-/unknown option
POSITIONAL+=("${arg}") # save it in an array for later
shift # past argument
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters
if [ -z "$access_token" ]
then
>&2 echo "WARNING: Access token not specified, though it is required!"
print_help
exit 1
fi
curl \
'https://api.github.com/graphql' \
-H 'Accept-Encoding: gzip, deflate, br' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Connection: keep-alive' \
-H 'Origin: altair://-' \
-H "Authorization: Bearer $access_token" \
--data-binary '{"query":"query { repository(owner: \"'$repo_owner'\", name: \"'$repo_name'\") { forks(first:100) { edges { node { nameWithOwner } } } } }","variables":{}}' \
--compressed \
> "$res_file"
cat "$res_file" \
| sed -e 's/nameWithOwner/\nXXX/g' \
| grep XXX \
| awk -e 'BEGIN { FS="\""; } { print $3; }'
您需要创建一个访问令牌。
上述脚本的示例调用:
git-hub-list-forks -o hoijui -r JavaOSC -t 1234567890abcdef1234567890abcdef
注意:GitHub 将一次获取的最大分叉数量限制为 100
推荐阅读
- javascript - 难以使用 API 组合参数?
- ios - 如何过滤比较 2 个 JSON 的数据并将结果保存在数组中
- python - Python从列表中每个项目的开头和结尾删除换行符
- xml - 是否存在比 ADODB.Stream 更快的替代方案?
- android - 意图构造之间有什么区别
- c++ - JUCE:滑块,ValueTree 错误
- azure-devops - 在 Azure Devops 中开始开发新模块时应该做些什么?
- react-native - 从 cameraRoll Uri 反应原生渲染图像
- javascript - 将对象序列化为 indexedDB 与 JSON.stringify 的效率
- sql - 错误:不允许组功能