バッチ処理の途中にブランチを作成したり削除したりしたくなった時はAPIでできます。
準備
githubのpersonal access tokenが必要です。(作成方法は割愛)
ブランチ削除
削除は簡単です。
curl -s -X DELETE -u [user]:[token] https://api.github.com/repos/[owner]/[repo]/git/refs/heads/[branch]
例えば nysalor/foo_proj
の feature/bar
を削除するなら
curl -s -X DELETE -u [user]:[token] https://api.github.com/repos/nysalor/foo_proj/git/refs/heads/feature/bar
ブランチ作成
作成はちょっと複雑で二段階になります。
SHA取得
まず作成元のブランチのSHAを得ます。(この例ではmasterから作成します)
curl -s -u [user]:[token] https://api.github.com/repos/[owner]/[repo]/git/refs/heads/master
jsonでオブジェクトの情報が返るのでSHAを切り出します。
{
"ref": "refs/heads/master",
"node_id": "xxxx==",
"url": "https://api.github.com/repos/[owner]/[repo]/git/refs/heads/master",
"object": {
"sha": "xxxx",
"type": "commit",
"url": "https://api.github.com/repos/[owner]/[repo]/git/commits/xxxx"
}
}
なお、jq
を使えば一発でSHAを切り出せます。
SHA=$(curl -s -u [user]:[token] https://api.github.com/repos/[owner]/[repo]/git/refs/heads/master | jq -r .object.sha)
ブランチ作成
SHAからブランチを作成します。
curl -s -X POST -u [user]:[token] -H "Content-Type: application/json" -d '{"ref": "refs/heads/[branch]", "sha": "'[上記で得たSHA]'"}' https://api.github.com/repos/[owner]/[repo]/git/refs
例えばS nysalor/foo_proj
のmasterから feature/bar
を作成するなら
SHA=$(curl -s -u [user]:[token] https://api.github.com/repos/nysalor/foo_proj/git/refs/heads/master | jq -r .object.sha)
curl -s -X POST -u [user]:[token] -H "Content-Type: application/json" -d '{"ref": "refs/heads/feature/bar", "sha": "'$SHA'"}' https://api.github.com/repos/nysalor/foo_proj/git/refs