PythonでGitリポジトリを自動制御するための方法を、実用的なサンプルコードとともに体系的にまとめました。
自動化、バッチ処理、CI/CD、DevOpsなどで「PythonからGitを操作したい」方に最適なリファレンスです。
GitPythonのインストール
まずはGitPythonをインストールします。
pip install gitpython
リポジトリの基本操作
既存リポジトリの読み込み
from 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コマンド | 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('ブランチ名') |
トークン認証付きリモート操作(GitHub例)
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')
実践的な活用例
- CI/CDでの自動コミット&プッシュ
- 複数リポジトリの一括操作(バッチ処理)
- 定期的なリポジトリのバックアップ
- 自動マージや自動ブランチ作成ツールの作成
トラブルシューティング・注意点
- GitPythonは内部でGitコマンドを呼び出すため、Git本体がインストールされている必要があります。
- 大規模リポジトリや大量ファイル操作時はメモリ使用量に注意。
- 認証トークンは環境変数や秘密管理ツールで安全に管理しましょう。
まとめ
- PythonでGitを制御するならGitPythonが最も手軽で強力
- 主要なGit操作はすべてPythonコードで自動化可能
- トークン認証やバッチ処理にも柔軟に対応
- 自動化・効率化・DevOpsに最適
コメント