LoginSignup
3
2

More than 3 years have passed since last update.

github apiでブランチの作成と削除を行う

Last updated at Posted at 2019-08-22

バッチ処理の途中にブランチを作成したり削除したりしたくなった時は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_projfeature/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
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2