LoginSignup
11
10

More than 5 years have passed since last update.

pythonからgit diffの内容を取得する

Posted at

経緯

gitでyamlのdiffだけ文字列で取得したくなった

pythonからgit使う

gitpython っていうのでgitの情報をいただく
pipで入る

pip install gitpython

ドキュメントはこちら
https://pythonhosted.org/GitPython/0.3.1/reference.html

こんな感じで使えました

diff.py
# coding: utf-8

import git
from . import PATH

"""
git diff HEAD HEAD^
したときに .yamlファイルの差分だけ文字列でとりたい
"""


class Diff(object):
    """HEAD と HEAD^ の差分のdiffをyamlのだけ引いてくれる"""

    DELIMITER = "\n\n"

    def __init__(self, repo_path):
        self.repo = git.Repo(repo_path)
        self.head = self.repo.head.commit
        self.parent = self.head.parents[0]

    def yaml_diff_as_patch(self):
        yaml_diffs = [
            unicode(d.diff) for d
            in self.parent.diff(self.head, 
                                create_patch=True)
            # .yamlって言う名前のファイルのみ
            if d.b_blob.name.endswith('.yaml') 
        ]
        return self.DELIMITER.join(yaml_diffs)


if __name__ == '__main__':
    obj = Diff(PATH)
    print obj.yaml_diff_as_patch()
11
10
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
11
10