PythonでGitリポジトリを自動制御するための方法を、実用的なサンプルコードとともに体系的にまとめました。
自動化、バッチ処理、CI/CD、DevOpsなどで「PythonからGitを操作したい」方に最適なリファレンスです。
まずはGitPythonをインストールします。
pip install gitpythonfrom git import Repo
repo = Repo('/path/to/your/repo')from git import Repo
new_repo = Repo.init('/path/to/new/repo')from git import Repo
Repo.clone_from('https://github.com/ユーザー名/リポジトリ名.git', '/path/to/clone')repo.index.add(['ファイル名.py'])repo.index.commit('コミットメッセージ')repo.index.remove(['削除するファイル.py'])
repo.index.commit('ファイル削除コミット')new_branch = repo.create_head('feature/new-feature')
new_branch.checkout()repo.git.checkout('main')branches = [b.name for b in repo.branches]
print(branches)origin = repo.remote(name='origin')
origin.push()origin.pull()origin.fetch()for commit in repo.iter_commits('main', max_count=5):
print(commit.hexsha, commit.author.name, commit.message)diff = repo.git.diff('HEAD~1', 'HEAD')
print(diff)print(repo.git.status())| Gitコマンド | Pythonコード例 |
|---|---|
| git status | repo.git.status() |
| git checkout -b branch | repo.git.checkout('-b', 'branch') |
| git reset –hard HEAD | repo.git.reset('--hard', 'HEAD') |
| git cherry-pick <commit> | repo.git.cherry_pick('コミットID') |
| git log | repo.git.log() |
| git diff | repo.git.diff() |
| git merge <branch> | repo.git.merge('ブランチ名') |
import os
from git import Repo
token = 'YOUR_GITHUB_TOKEN'
url = f'https://{token}@github.com/ユーザー名/リポジトリ名.git'
repo = Repo('/path/to/your/repo')
if 'origin' not in [remote.name for remote in repo.remotes]:
origin = repo.create_remote('origin', url)
else:
origin = repo.remote('origin')
origin.push(refspec='main:main')