10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでgitの操作をラッピング

Posted at

自分用メモ。
PythonでGitの動きを把握するには、subprocess モジュールの Popen を使う。


class GitError(BaseException): pass


def git(cmd, *args):
     command = ("git", cmd) + args
     proc = Popen(command, stdin=-1,stdout=-1,stderr=-1)
     out, err = proc.communicate()

    if len(err) == 0:
        return out.strip()
    else:
        raise GitError(err.strip())

これを応用した、GitUtility というクラスを作ってみる。

from subprocess import Popen

class GitError(BaseException):
    """
    This Error raises when git command runner has error.
    """

    pass

class GitUtility(object):
    """
    The GitUtility contains utility functions for operate git.
    """

    def __init__(self):

        return

    def run(self, cmd, *args):
        """
        This command is git command runner by subprocess.
        Return output or raise GitError if runner has error.
        """

        if isinstance(args[0], tuple):
            # Avoid duplicate tuple
            # ex. self.rev_parse("--show-toplevel")
            #   ->('git', 'rev-parse', ('--show-toplevel',))
            command = ("git", cmd) + tuple([arg for arg in args[0]])
        else:
            command = ("git", cmd) + args

        proc = Popen(command, stdin=-1,stdout=-1,stderr=-1)

        out, err = proc.communicate()

        if len(err) == 0:
            return out.strip()

        else:
            raise GitError(err.strip())

    def add(self, path):
        """
        Run git add command
        """

        self.run("add", path)

    def commit(self, commit_msg):
        """
        Run git commit
        """

        return self.run("commit", "-m", commit_msg)

    def rev_parse(self, *args):
        """
        Run git rev-parse command
        """
        return self.run("rev-parse", args)

    def get_toplevel(self):
        """
        Return git top level path using git rev-parse
        """

        return self.rev_parse("--show-toplevel")

たとえば自動でコミットさせたいとか、rev-parse を使ったリポジトリのパスを取得したいとか、そういうことができる。
もっと応用すれば、ログのパースとか、あるコミット時点のファイルの中身を取得できたりもする。

10
9
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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?