iMind Developers Blog

iMind開発者ブログ

Pythonからgitの操作

w## 概要

gitの操作をPythonから実行してみる。

cloneしてdiffを見てbranch切ってcheckoutしてcommitしてpushするまでを実行。

バージョン情報

  • Python 3.7.3
  • GitPython==2.1.11

インストール

$ pip install GitPython

clone

import git

# urlは適宜自身が編集可能なレポジトリに書き換えてください
url = 'https://github.com/imind-inc/blog.git'

# cloneしたプロジェクトを出力するパス
to_path = 'foo'

git.Repo.clone_from(
    url,
    to_path)

これでto_pathで指定したfooディレクトリにcloneされる。

untrack_files

untracked_filesの確認。

# to_pathで指定したディレクトリ配下に新規ファイルを作成
with open('foo/bar.txt', 'wt') as fp:
    fp.write('hogehoge')

# untracked filesの確認
repo = git.Repo(to_path)
repo.untracked_files
    #=> ['bar.txt']

diff

HEADとのdiffを取る。

repo.git.diff('HEAD')

log

iter_commits でコミット情報をiteratorで回して情報を表示。

for commit in repo.iter_commits('master'):
    print(commit.author,
        commit.committed_datetime,
        commit.hexsha)

各コミットのdiffを表示して回る。

for commit in repo.iter_commits('master'):
    print('|' * 55)
    print(commit.hexsha)
    print('|' * 55)
    for diff in commit.diff():
        print(diff)

branch

branchの取得。

repo.git.branch() 

    #=> '* master'

新規のbranch作成。

repo.git.branch('new_branch') 

repo.git.branch() 

    #=> * master
    #=>  new_branch

checkout。

repo.git.checkout('new_branch')

repo.git.branch() 

    #=>  master
    #=> * new_branch

addとcommit

適当なファイルに書き込み。

with open('foo/bar.txt', 'wt') as fp:
    fp.write('hogehoge')

add

repo.git.add('bar.txt')

commit

repo.git.commit('bar.txt', message='new file', author='watanabe')  

push

push

repo.git.push('origin', 'new_branch')

最後に作ってしまったremoteのbranchを削除して終了

repo.git.push('--delete', 'origin', 'new_branch')

改定履歴

Author: Masato Watanabe, Date: 2020-01-18, 記事投稿