gitpython つかってみた

目的

手順

いれる

$ pip install gitpython

こんな感じでリポジトリを仮に作ってみる

github.com

やりたいこと

  • git clone
  • git branch -b
  • git add
  • git commit

こんな感じで書く

import os
import git

_repo_path = os.path.join('./', 'repo')
# clone from remote
git_repo = git.Repo.clone_from('git@github.com:rane-hs/test.git', _repo_path, branch='master')
# create new branch from head
git_repo.checkout('HEAD', b='new_branch')

# 更新対象を生成
_test_dir = os.path.join(_repo_path, 'test1')
os.mkdir(_test_dir)
f = open(os.path.join(_test_dir, 'test.txt'), 'w', encoding='utf-8')
f.write('this is test')
f.close

# git add & commit
git_repo.index.add(['test1'])
git_repo.index.commit('new commit!')

# git push origin HEAD
git_repo.remotes.origin.push('HEAD')
# ここでパスとかなんやかんや聞かれる

その他

# from existing dir
git_repo= git.Repo(_git_dir)
# fetch all
git_repo.remotes.origin.fetch()
# origin/hogehoge があればここで自動でhogehogeになる。gitと動きは同じ
git_repo.git.checkout('hogehoge') 
git_repo.git.pull()

.git.{任意のコマンド} でたいていなんとかなる

次回予告

  • github3pyを使ってPRまで自動化しちゃおう!